Magazine

IFS and Loops in Linux Bash Script

Posted on the 22 April 2021 by Satish Kumar @satish_kumar86

The shell has oneenvironmentvariable, which isnamedtheInternal Field Separator(IFS). This variable indicates how the words are separated onthecommand line. TheIFSvariable is, normally or by default, a whitespace (”). TheIFSvariable is used as a word separator (token) for theforcommand. In many documents, IFS can be any one of the white spaces,:,|,:, or any other desired character. This will be useful while using commands such asread,set, andfor. If we are going to change the defaultIFS, then it is a good practice to store the original IFS in a variable.

Later on, when we have done our required tasks, then we can assign the original character back to IFS.

In the following  for_16.sh script, we are using: as the IFS character:

for_16.sh

#/bin/bash 
cities=Delhi:Chennai:Bangaluru:Kolkata 
old_ifs="$IFS"           # Saving original value of IFS 
IFS=":" 
for place in $cities 
do 
      echo  The name of city is $place 
done 

Let’s test the program:

$ chmod +x for_16.sh
$ ./for_16.sh

The following will be the output after executing the preceding commands:

Output:

The name of city is DelhiThe name of city is ChennaiThe name of city is BangaluruThe name of city is Kolkata

By default, the original inter-field separator is a whitespace. We have saved the original IFS in the old_ifs variable. We assigned a colon : and an IFS in the script. Therefore, we can use : as an inter-field separator in our test file or text string.


Back to Featured Articles on Logo Paperblog