Sunday, January 21, 2007

Unix shell: Finding the run-time directory of a script

I've been trying to come up with an elegant way, in a shell script, to find the full path of the directory in which the script is located.

So far, I have this, which works for bash but not for sh (sh does not support substring expansion on variables):


 #!/usr/local/bin/bash -x
# Finds the full path to the directory containing this script

dir_containing_this_script=""
script_dirname=`dirname $0`
first_char="${script_dirname:0:1}" ; # Starting at index 0, 1 character
case "$first_char" in
("/")
# It's a full path. Use it unmodified.
dir_containing_this_script="${script_dirname}"
;;
(*)
# Strip leading . characters
while [ "${first_char}" = "." ]; do
script_dirname="${script_dirname:1}" ; # substring from index 1 to end
first_char="${script_dirname:0:1}"
done
current_dir=`pwd`
if [ -s "${script_dirname}" ] ; then
dir_containing_this_script="${current_dir}/${script_dirname}"
else
dir_containing_this_script="${current_dir}"
fi
;;
esac

echo "$dir_containing_this_script"


Update: Eric M on The WELL posted this most excellent solution:

dn=`dirname $0`
path=`(cd $dn; pwd)`
echo "path = $path"

Technorati Tags: , ,

1 comment:

Unknown said...

Probably obvious, but collapsed to one line:

path=$( cd $( dirname $0 ) ; pwd )

Regardless of how you do it, please make a comment in your script to explain it to any future maintainers.