Continuing from the comment and explanation of word-splitting and the Internal Field Separator, here is a short example that should help:
#!/bin/bash
list="one two three"
printf "\nDefault IFS (space, tab, newline):\n\n"
for a in $list
do
echo "$a"
done
for a in "$list"
do
echo "$a"
done
printf "\nIFS breaking only on newline:\n\n"
IFS=$'\n'
for a in $list
do
echo "$a"
done
for a in "$list"
do
echo "$a"
done
(if you continue in a script and don't exit after setting IFS
to a new value and need to restore the current (or default) IFS
, either save the current (e.g. curifs="$IFS"
and restore when done with your block, IFS="$curifs"
) or just reset to the default (e.g. IFS=$' \t\n'
). you can also, just run your block with the new IFS
in a subshell, e.g. (IFS=$',\n'; #do stuff)
, or in a while
block, e.g. while IFS=$'\n' read -r line; do ...
)
Example Use/Output
$ bash ifs.sh
Default IFS (space, tab, newline):
one
two
three
one two three
IFS breaking only on newline:
one two three
one two three