Search code examples
bashshellifs

Printing the IFS chars


I've noticed that to print the value of the $IFS variable in the shell I have to do something like:

$ printf '%s\nYour IFS is: %q' 'Hello' "$IFS"
Hello
Your IFS is: $' \t\n'

My question is why do I need to pass the IFS in that special way? For example, why (or why wouldn't) it be possible to do:

  • $ echo $IFS -- some parameter that prints special characters?
  • $ printf "$IFS" or $ printf '$IFS' -- why wouldn't either of these work?
  • Why $ printf "%q" $IFS and $ printf "%q" '$IFS' don't show this properly but $ printf "%q" "$IFS" does?

Solution

    • $ echo $IFS -- some parameter that prints special characters?

    echo doesn't have such a parameter

    • $ printf "$IFS" or $ printf '$IFS' -- why wouldn't either of these work?
    1. The first does interpolation of the string just like echo does and prints the IFS string just like it is - which by default is a bunch of whitespaces.
    2. The second does not do interpolation and obviously prints $IFS.
    • printf "%q" $IFS

    The variable has already been expanded into whitespaces that are eaten up by the shell so nothing is passed as a second parameter to printf and therefore %q has no input to work with.

    • printf "%q" '$IFS'

    The string $IFS is passed as a parameter to %q which just adds escape characters to it.