command line fun – getting to the base of things

Just a short time back I received a mail from a colleague with an error message.  The question from him was about the error and more importantly was this my program.  I did find some code that generated the same message but it wasn’t installed.  Well, it appeared to be installed but it wasn’t being run.

I was really in the middle of another issue so I asked my colleague to take a closer look into it.  She actually found a slightly modified version of the code and it wasn’t installed in the normal location. She didn’t think that this was being run either as no log file was placed into the log directory.

Too clever by far.  The developer did a few small changes using the basename and dirname commands and leaving almost everything else the same.

These commands are essentially a ying and yang to each other.  The basename command will strip off the path and return only the command, while the dirname command will remove the program and return the path.

command argument result
basename /home/bob/listing.sh listing.sh
dirname /home/bob/listing.sh /home/bob

Changed both the input and output directories relative to the installation directory.  Using either basename or dirname is a rather exotic way of choosing where to get input or place output.  A much simpler choice would be to use the current working directory.

#!/bin/bash
LOGFILE=`pwd`/logfile.txt
echo $((5 + 6)) >$LOGFILE

Yet this won’t work unless you run it from the installation directory.  If you run this script from another directory, the output will end up there.  The same general fate will occur if you try and run the script from the crontab.

When running scripts from the crontab the script is run from the root directory.  So this script would probably not work as the output cannot be written to the root.  Thus the clever solution is the one that is necessary.

#!/bin/bash
LOGFILE=`dirname $0`/logfile.txt
echo $((5 + 6)) >$LOGFILE

Using the dirname command on the name of the script that is being run will then actually be the same effect as having a variable for the installation directory.

 

This entry was posted in Command line, programming and tagged , . Bookmark the permalink.