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: programming, unix, unix shell
1 comment:
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.
Post a Comment