💻 syscmds.net

Change splitting in Bash

By default a bash for loop will split on spaces, tabs and newlines. Take the following example:

input="first line
second line"

for entry in $input; do
    echo "Entry: $entry"
done

In this case, four entries will be produced. What if the splitting should instead be done only per line? To achieve this it is necessary to set the IFS variable. This is short for Internal Field Separator.

# Set the IFS to separate on new lines
IFS=$'\n'

input="first line
second line"

for entry in $input; do
    echo "Entry: $entry"
done

Note that special 'ANSI C Quoting' is used to ensure that the newline is not treated literally. IFS can be set at any point during the script. It may be beneficial to preserve the initial IFS and set this at the end of processing if integrating with a larger bash script to prevent any unintentional change in behaviour.

Further information can be found within the bash man page. Type man bash and then search for IFS.

Last Modified:
Tags: bash