When using /bin/bash, what is the difference between the following two cases:

  • echo $IFS
  • echo "$IFS"

I observe different outputs.

  • 1
    why don't you illustrate the difference – Lee Sep 11 '15 at 20:44
  • This is not a good question, because the information you need about quoting and expanding Bash variables, including IFS, is all over the Internet (including this site). – blujay Sep 12 '15 at 0:59

"$IFS" will be a single argument. The function of the "" is that it bounds the spaces in them into a single word, with spaces.

For example, if IFS contains a__b (imagine spaces instead of the _s), then

echo "$IFS" will be after the variable substutition: echo "a b", thus the echo command will get a single argument. Thus, it will print: a b.

While echo $IFS will be substituted to echo a b, which will mean, that echo gets two arguments: an a and a b. So, it will print: a b.

There are other differences as well, for example if IFS contains an enter, it will be also hidden in the first version, but not in the second.

  • I didn't get this part: echo "$IFS" will print: a b while echo "$IFS" will print a b ? – Jake Sep 11 '15 at 19:38
  • @Jake I fixed the syntax and elaborated, how is it looking now? – peterh Sep 11 '15 at 19:41
  • So with double quotes, a series of spaces is unioned together with adjacent characters and then presented to echo ? – Jake Sep 11 '15 at 19:45
  • 1
    @Jake No: by default, bash gets a line of characters as the command to execute. It splits this line to induvidual strings. This split doesn't happen between the double quotes. (And, between single quotes, even the variable names won't be substituted after the $, so echo '$IFS' will print $IFS.) – peterh Sep 11 '15 at 19:51
  • 2
    @peterh Note the difference between echo $IFS | cat -vet and echo "$IFS" | cat -vet. The tab and newline are ignored in the unquoted variable and the space is null in echo's arguments. – fd0 Sep 11 '15 at 20:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.