Bash – Help with bash script

bashforpath

I am teaching myself bash scripting with the book 'Learning the Bash Shell' by Newbam. I'm getting on OK with the book, but am a bit confused by the following script. It is a script which uses a for loop to go through the directories in $PATH, and print out information about them. The script is

IFS=:
for dir in $PATH; do
 if [ -z "$dir" ]; then dir=.; fi
 if ! [ -e "$dir" ]; then
 echo "$dir doesn't exist"
 elif ! [ -d "$dir" ]; then
 echo "$dir isn't a directory"
 else
  ls -ld $dir
done

What I'm confused about is why if dir is zero, or doesn't exist, are we then setting this null value to be the current directory? Or are we changing dir to our current directory (whatever directory we happen to be in) ? The script then seems to test if dir exists, and then tests if it is a directory.

Can anybody shed light on this aspect of the script for me? I would have thought that if [ -z "$dir" ] was true, that this would indicate that the directory doesn't exist, and isn't a directory to begin with?

Best Answer

The -z test is testing for a zero-length value in $dir, not for anything related to an actual directory. That condition is triggered if you have a :: sequence in your PATH variable, at which point we set the value of the $dir variable to ., meaning the current directory, and we then conduct the standard two tests on it.

Related Question