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

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

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




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




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |