Bash IFS & word splitting


Example

See what, when and why if you don't know about the affiliation of IFS to word splitting

let's set the IFS to space character only:

set -x
var='I am
a
multiline string'
IFS=' '
fun() {
    echo "-$1-"
    echo "*$2*"
    echo ".$3."
}
fun $var

This time word splitting will only work on spaces. The fun function will be executed like this:

fun I 'am
a
multiline' string

$var is split into 3 args. I, am\na\nmultiline and string will be printed

Let's set the IFS to newline only:

IFS=$'\n'
...

Now the fun will be executed like:

fun 'I am' a 'multiline string'

$var is split into 3 args. I am, a, multiline string will be printed

Let's see what happens if we set IFS to nullstring:

IFS=
...

This time the fun will be executed like this:

fun 'I am
a
multiline string'

$var is not split i.e it remained a single arg.

You can prevent word splitting by setting the IFS to nullstring

A general way of preventing word splitting is to use double quote:

fun "$var"

will prevent word splitting in all the cases discussed above i.e the fun function will be executed with only one argument.