« Knobtweakers | Main | The watch & pgrep Commands »

showpath (a rare $IFS sighting)

How do you view the contents of your $PATH? If you're like most people, you just say:

echo $PATH

In one of my previous jobs, our servers had a hideously long and complicated $PATH. Complicated things break, so every once in awhile I'd find myself grovelliing through it trying to figure out what was happening. That didn't happen more than a couple of times before I decided that I needed an easier solution. And thus was showpath born:

function showpath {
   local IFSBAK=$IFS
   local DIRS=""
   IFS=':'
   echo 'PATH:'
   for i in $PATH
   do
       DIRS="$DIRS
       $i"
   done
   echo $DIRS | sort
   IFS=$IFSBAK
}

The most interesting part of this script is probably $IFS. When the shell interprets a command, it actually tokenizes twice. The second tokenization happens after variable expansion. Most of the time, it splits on whitespace*. However, as the example above shows, you can change that by assigning a different value to $IFS. In the case of showpath I wanted to iterate over each directory in $PATH so I set $IFS to split on colons.

*In my experience, the second tokenization is one of the most common causes of shell script bugs. Performing tokenization a second time can be useful, but few people expect it. Hence Stuart's Rule of Shell Variables: Always put variables in double quotes (unless you have a very good reason not to).