How many times in Linux shell scripting 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 Separator holds the value which separates the various entities. This can be file names, values read 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 nonprintable characters , tabs as ^I and ends each line with a $ sign.
In a script which utilizes 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. Let us check out one such script which accepts filenames with spaces. This scripts simply prints the file names in your current directory. (Remember to create some files in your current directory which has spaces. You may try the same script removing the lines with the IFS variable in reference to seeing 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.