Bash Coding Convention ../

We use dirname() a lot in php to make relative paths work from multiple locations like so. The advantages are many:

require dirname( dirname( __FILE__ ) ) . '/required-file.php';
$data = file_get_contents( dirname(__FILE__).'/data/info.dat');

But in bash we often dont do the same thing, we settle for the old standby “../”. Which is a shame because unless your directory structure is set up exactly right, and you have proper permissions, and you run the command from the right spot, it doesnt work as planned. I think part of the reason is that its not obvious how to reliably get a full path to the script from inside itself. Another reason is that ../ is shorter to type and easier to remember. Finally there’s always one time scripts for which this methodology is overkill. But if you’re planning to write a script which other people will (or might) be using, I think it’s good practice to do it right. Googling for things you’d think to search for on this subject does not yeild very informative results, or incomplete (incorrect) methods… so… here’s how to do the above php in bash:

source $(dirname $(dirname $(readlink -f $0)))/required-file.sh 
data=$(cat $(dirname $(readlink -f $0))/data/info.dat)

Hope this helps someone 🙂

As a side note, the OSX readlink binary functions differently. You’ll want to use a package manager to install gnu coreutils, and iether use greadlink, or link greadlink to a higher precedence location on your $PATH (I have /opt/local/bin:/opt/local/sbin: at the beginning of my $PATH)

3 thoughts on “Bash Coding Convention ../

  1. Mike Brittain says:

    My bash is pretty rickety, and this is exactly the sort of thing I'm always trying to do. Very helpful tip.

  2. Matthew Tardiff says:

    It's interesting that I accidentially ran across this. A few months ago I was looking for a way to achieve this. I couldn't find anything at the time, so I came up with this solution:

    readonly SCRIPT_DIR="$( dirname "$( which "$0" )" )"

    My solution depends on bash 3.2 however, for the "which" builtin.

Leave a Reply to Matthew TardiffCancel reply