: # scriptpath - determine own absolute path name # Heiner Steven , 2003-01-06 # # Searches for the name of the script ($0) the way a shell would: first # try to access the file directly, then search all directories in # $PATH. # # Notes # o The results are always unsure, because the program invoking the # script may have set $0 to an arbitrary (even wrong) value. # o We check if a file is an regular file and if it is executable. # Remove the [ -x ... ] checks if the former is sufficient. myname=$0 # When "CDPATH" is set, "cd" sometimes prints the destination directory # to standard output, which could corrupt x=`cd` output: unset CDPATH if [ -f "$myname" ] && [ -x "$myname" ] then # $myname is already a valid file name. Chances are good # that it is our name. mypath=$myname else case "$myname" in /*) # absolute path - do not search PATH echo >&2 "cannot find full path name: $myname" exit 1 ;; *) # Search all directories from the PATH variable. Take # care to interpret leading and trailing ":" as meaning # the current directory; the same is true for "::" within # the PATH. for dir in `echo "$PATH" | sed 's/^:/.:/g;s/::/:.:/g;s/:$/:./;s/:/ /g'` do #echo >&2 "DEBUG: dir=<$dir>" [ -f "$dir/$myname" ] || continue # no file [ -x "$dir/$myname" ] || continue # not executable mypath=$dir/$myname break # only return first matching file done ;; esac fi if [ -f "$mypath" ] then : # echo >&2 "DEBUG: mypath=<$mypath>" else echo >&2 "cannot find full path name: $myname" exit 1 fi # "Normalize" the path: resolve /./ and /../ directory specifications dir=`echo "$mypath" | sed 's|^\(.*\)/[^/]*|\1|'` # dirname file=`echo "$mypath" | awk -F/ '{print $NF}'` # basename #echo >&2 "DEBUG: dir=<$dir> file=<$file>" if [ X"$dir" != X ] && [ -d "$dir" ] then dir=`cd "$dir"; pwd` # "pwd" always prints "normalized" paths abspath=$dir/ else abspath= fi abspath=$abspath$file echo "$abspath" exit 0