Tuesday, March 29, 2011

From within a bash executing script, how do I find the directory where the script lives?

A simple pwd doesn’t work because it gives the Present Working Directory, and we want to know the directory where the script actually resides on disk. I can’t remember the previous solution I came up with, but here’s another solution that should work:


#!/bin/bash
dir=$(echo $0 | sed -e "s,\([/]\),$(pwd)/\1,")
echo I live in $dir

Here is how it works (hopefully). $0 is the name of the script as it was executed, so this may be foo.sh, ./foo.sh, /tmp/foo.sh, etc.. This gets sent to sed, which then uses a basic regular expression that says “If the first character of $0 was NOT a forward slash, then prepend $0 with my present working directory ($(pwd)) followed by whatever that first character was (\1), then assign this new value to dir”. If the first character in $0 is a forward slash, then we were invoked via an absolute path and so we don’t want to change anything.