IFS

How many times have you written scripts and a had bad time with those having spaces? The remedy to this situation is your IFS value.

IFS or Internal Field Seperator holds the value which seperates the various entities. This can be file names, values read into a script by read etc. It is the character or characters designated as whitespace by the operating system.

The IFS is set to the newline and space character. The global variable $IFS stores the value. To view the exact value stored in IFS execute:

echo "$IFS" | cat -vTE
 ^I$
$

Running echo “$IFS” will not give you any visible output (after all, you are going to see a space and a newline). cat -vTE displays non printable characters , tabs as ^I and ends each line with a $ sign.

In a script which utilises filenames (with spaces), it is always preferable to change the IFS to include only the newline character opposed to the default space and newline character. Lets check out one such script which accepts filenames wih spaces. This scripts simply prints the file names in your current directory. (Remember to create some files in your currenct directory which has spaces. You may try the same script removing the lines with the IFS variable in reference to see the difference)

#!/bin/bash
OIFS=$IFS # Original IFS

IFS=$(echo -en "\n\b") # New IFS

for fil in $(ls -1 $PWD); do
	echo $fil
done

IFS=$OIFS # Restore earlier IFS

IFS can also be used to read files with lines sepearated by a special character. For example in the /etc/passwd, to store the various entries like username, homedirectory etc.

The following script uses the while construct to determine the users who have the shell portion as /bin/false

#!/bin/bash

OIFS=$IFS
IFS=':'

while read username password userid groupid comments homedir shell_avail
do
	if [[ $shell_avail == /bin/false ]]; then
                echo "$username has no shell"
        fi

done < /etc/passwd
IFS=$OIFS

In the above script each of the 7 portions of the /etc/passwd file is assigned to the 7 variables
username password userid groupid comments homedir shell_avail with the read command. The if portion in the script compares the seventh variable – shell_avail to /bin/false to determine the username and outputs it.

From now on you can use the IFS variable for all those files with spaces and extracting values separated by a special character.

Continue Reading


 

About this blog

This blog, acts as a knowledge repository for the world and is unofficial! Anything we find interesting in the cyber world will go here. Most cases, this blog will reflect the happiness of our staff in reaching successful solution to an issue (s)he worked on. A reference for other fellow SAGEs who come across similar issues later