Search code examples
bashechoifs

Why does default $IFS expand to a newline, when "for word in $string" splits on spaces?


When I execute the code below via command line:

(
    mystring="foo:bar baz rab"
    for word in $mystring; do
      echo "Word: $word"
    done
)

The result I get is:

Word: foo:bar
Word: baz
Word: rab

This means that the $IFS would be interpreted as a space character. But then I try to reverse it by doing the following:

echo "foo:bar${IFS}baz${IFS}rab"

And prints:

foo:bar
baz
rab

Which now means the $IFS is a \n. I would have expected "foo:bar baz rab"

What is causing this inconsistency?


Solution

  • IFS contains three characters by default: Space (first), tab (second), newline (third).

    This means any one of these three characters can act as a word separator. $* uses only the first of those three to separate words.

    If you want to generate a string from an array, separated by the first character in IFS, consider:

    # Combine array elements with the first character in IFS using ${array[*]}
    array=( foo:bar baz rab )
    echo "${array[*]}"