Skip to main content
Bash

What is IFS in Bash Scripting?

The IFS in bash comes in handy when you are dealing with a different delimiter than the usual space, tab or newline.

Helder

Warp Terminal

When doing Bash scripting, or simply coding on your Linux server through its command line, the flexibility that Linux can give you is remarkable.

IFS or Internal Field Separator, is just a simple way to tell the system (or more specifically, the current terminal session) to consider a particular symbol or character in your field separator. This allows, within a bash script to be able to make the system work with a particular character as its separator.

By default, the IFS in bash and many other shells are space, tab and newline. But you can explicitly specify it in your bash script and change it as per your need.

How can IFS be useful?

Pretty simple! Let's say you are working with Comma Separated Values files (CSV), and you want to use a script to be able to read through this file to be able to work with its data.

As you know, each "," is going to separate the fields or important data contained in this file. Hence, that's what you need to tell the system.

Let's do a very simple example, where we have a file: clients.csv, that holds First Name, Last Name, Age, and Country:

IFS=","
while read -r field1 field2 field3 field4; do
   echo "First Name: $field1"
   echo "Last Name: $field2"
   echo "Age: $field3"
   echo "Country: $field4"
done < clients.csv

This script will read through that file, understanding the "," is the field separator, and store this in variables through the file and output these with the respective field name.

Here's an example run of the above scenario with a sample csv file:

Making it persistent

You might prefer to have this IFS changed persistently, and not only for the current terminal session, in this case, you will need to set the IFS value in your “.bashrc” or “.bash_profile” file.

Bash Scripting Tutorial Series for Beginners [Free]
Get started with Bash Shell script learning with practical examples. Also test your learning with practice exercises.

Conclusion

Linux is so powerful and yet flexible, it allows you to control things such as how fields are separated and use a common character to be able to work with your scripts.

Using IFS to set this character depending on the objective you want to pursue with your script. It allows you to be able to do scripts that can do things such as selecting different parts of your inputs and massaging your data to simply work with it, create new arrays and innumerable things more.

I hope you like this quick little article on IFS in bash shell. Let me know if you still have any questions or suggestions.

Helder
@heldmar Montevideo, UY