$IFS
There is a built-in shell variable, $IFS
(Internal Field Separator). It is used automatically to determine how, for example, word splitting should be done during expansion or when we use the read variable. It contains by default space, tab, newline and that is how the strings will be separated. We can change it and decide how we want it to be separated.
We look at how word splitting is used with IFS in default mode:
#!/usr/bin/env bash
#
# An example script on IFS and word splitting
sentence="Bash is awesome"
for word in $sentence
do
echo "$word"
done
We will get the result:
Bash is awesome
It works just as planned. If we had another string to work with, perhaps we would have needed to change IFS:
#!/usr/bin/env bash
#
# An example script on IFS and word splitting
sentence="Bash:is:awesome"
for word in $sentence
do
echo "$word"
done
The string is not splitted as intended:
Bash:is:awesome
We need to change IFS.
#!/usr/bin/env bash
#
# An example script on IFS and word splitting
sentence="Bash:is:awesome"
# Change the IFS
IFS=":"
for word in $sentence
do
echo "$word"
done
The string is now splitted on a delimiter:
Bash is awesome
If we want to change IFS, it can be good to reset it when you are done. It is automatically reset when we finish the script but if we change it in the middle we may need to reset it. Just make a backup before you change it:
#!/usr/bin/env bash
#
# An example script on IFS and word splitting
IFS_BACKUP=$IFS
# ...
# Do something with $IFS
# ...
# Reset the value
IFS=$IFS_BACKUP
# Continue with the default values
Tip 1: See what IFS contains: echo "$IFS" | cat -ETv
Tip 2: Read more about IFS