Bootstrap FreeKB - Bash (Scripting) - IFS (Internal Field Separator)
Bash (Scripting) - IFS (Internal Field Separator)

Updated:   |  Bash (Scripting) articles

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,  use new lines, and not whitespaces, 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 as the delimiter.

''

 

If you instead want the delimiter to be 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 uses new lines as the delimiter.

$'\n'

 

Now, the for loop will use newlines, and not whitespaces, as the delmiter.

#!/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 whitespaces, and not newlines, as the delmiter.

unset IFS

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter f7f041 in the box below so that we can be sure you are a human.