Bash – “echo $IFS” does not return the value of IFS

bash

I have set the IFS to x, i.e IFS=x. Now if I check the value of IFS, then it appears to be empty if I do not use double-quotes:

~ $ echo $IFS | cat -e
$
~ $ echo "$IFS" | cat -e
x$
~ $ echo $HOME   
/home/mar
~ $ echo "$HOME"
/home/mar
~ $ 

As seen above, $HOME does not behave like that. What is the reason for such behavior?

Best Answer

After the variable is expanded, word-splitting occurs and it gets split into empty word(s). Splitting is done using each character of the IFS variable as delimiter and since $IFS only expands to characters in the IFS it gets split into empty word(s).

So, for example:

IFS=xxx;
printf %q $IFS
''''''[root@localhost ~]#

And if you double quote, you are telling bash to treat everything inside the quotes as one word:

printf %q "$IFS"
xxx[root@localhost ~]#
Related Question