
Let's say you have an variable where each line is separated by a new line.
fruit="
apples are red
bananas are yellow"
By default, a for loop will use whitespaces, and not newlines, as the delmiter.
#!/bin/bash
fruit="
apples are red
bananas are yellow"
for myFruit in $fruit; do
echo $myFruit
done
In this example, the for loop will produce the following result.
apples
are
red
bananas
are
yellow
This is because the Internal Field Separator, commonly just known as IFS, uses whitespace, tabs and new lines as the delimiter. This can be seen by printing the IFS variable.
printf %q "$IFS"
Which should return the following, which means that IFS uses whitespace, tabs and new lines as the delimiter.
$' \t\n'
If you instead want the delimiter to be just new lines, IFS can be used to set new lines as the delimiter.
IFS=$'\n'
Printing the IFS variable.
printf %q "$IFS"
Should now return the following, which means that IFS will only use new lines as the delimiter.
$'\n'
Now, the for loop will only use new lines as the delimiter.
#!/bin/bash
IFS=$'\n'
fruit="
apples are red
bananas are yellow"
for myFruit in $fruit; do
echo $myFruit
done
unset IFS
Which should now return the following.
apples are red
bananas are yellow
Optionally, you can use the unset command to return IFS to use whitespace, tabs and new lines as the delimiter.
unset IFS
Did you find this article helpful?
If so, consider buying me a coffee over at