Geoff Garbers

Husband. Programmer. Tinkerer.

Retrieving the current script's directory in bash

May 30, 2011

Whenever I like to write a bash script, I like to ensure that whatever script I’m writing is as portable as possible. One thing that I find quite useful is basing all my paths on the currently executing file’s directory.

However, there’s no single command to get the currently executing script’s directory.

But there is a way to get this directory, but it involves a little bit of trickery. I’ve shown how to do this below:

    # Set the current directory to be the dirname of the current file.
    HERE=`dirname "$0"`
    
    # If not absolute path to file, then get as absolute.
    if [ `echo "${HERE}" | /usr/bin/cut -b 1 -` != "/" ] ; then
        HERE=`dirname $(pwd)/"${0}"`
    fi