I am trying to store words from an input as parameters with read -p as follows :

    read -p "Enter your command: " cmd arg1 arg2
    echo "$cmd"
    echo "$arg1"
    echo "$arg2"

With this, $cmd contains all 3 inputs separated by spaces, $arg1 and $arg2 are empty. Any idea why?

  • What is the value of $IFS? – nohillside May 15 '19 at 18:54
  • @nohillside it returns ':' – Nawra C May 15 '19 at 19:29
  • Set IFS back to its default. In other words, add the command IFS=$' \t\n' before the read command. – David Anderson May 15 '19 at 19:31

The variable IFS is used by various commands. The safest thing to do is save the value, then restore when finished. Below is an example.

declare "IFS_BACKUP=$IFS"
IFS=$' \t\n'
read -p "Enter your command: " cmd arg1 arg2
echo "$cmd"
echo "$arg1"
echo "$arg2"

The documentation command man bash defines IFS as follows:

   IFS    The  Internal  Field  Separator  that is used for word splitting
          after expansion and to split lines  into  words  with  the  read
          builtin  command.   The  default  value  is  ``<space><tab><new-
| improve this answer | |
  • Thanks, this worked. I will try understanding more about IFS – Nawra C May 15 '19 at 19:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .