Explaining the default field separator field - IFS

The final thing in this chapter has got to do with the input field separator (IFS). We've looked at the IFS variable previously, if you type:

set |grep IFS
            

You will see that IFS is probably set to

IFS='\t\n '
            

That means that the IFS is set to a tab, a newline or a space. If you needed to change this to a comma for the duration of a script, you would say:

(IFS=',';script.sh)
            

That would set the IFS to a comma for the duration of that script - notice the round brackets which execute this as a subshell leaving our original IFS untouched.

Changing the IFS will change the field separator for a script or a command, and this is something to be aware of as up to now all the commands that we have used in the entire course use the default IFS. (ls -al will no longer work if you have changed the IFS to be a colon!)

If for example we were parsing our /etc/passwd file, where fields are separated by a colon ( : ) or a newline (\n), then using IFS=':\n' would work for us.

IFS=":\n"
while read username ex uid gid gecos homedir shell
do
	echo $username belongs to the user $gecos
done < /etc/passwd