The Problem
Sometimes in a script you just need a full path to where a script resides. In bash the common way to get the script's location is `dirname $0`
This only gives the relative path if you run the script with ./scriptname or ../scriptname (../bin/scriptname etc).
Following are several alternatives to get the full path (directory name specified from root /)...
The Script
#!/bin/sh
# different methods of trying to identify the current path
echo "basename = "`basename $0`
echo "dirname = "`dirname $0`
echo "0%%/* = ${0%%/*}"
LSOF=$(lsof -p $$ | grep -E "/"$(basename $0)"$")
MY_PATH=$(echo ${LSOF} | sed -E s/'^([^\/]+)\/'/'\/'/1 2>/dev/null)
MY_ROOT=$(dirname ${MY_PATH})
echo "LSOF = ${LSOF}"
echo "MY_PATH = ${MY_PATH}"
echo "MY_ROOT = ${MY_ROOT}"
script_dir_link=$(dirname "$(readlink "$0")")
[[ ${script_dir_link} == "." ]] && script_dir=$(dirname "$0") || script_dir=${script_dir_link}
echo "script_dir_link = ${script_dir_link}"
echo "script_dir = ${script_dir}"
abspath=`dirname $(cd "${0%/*}" 2>/dev/null; echo "$PWD"/"${0##*/}")`
echo "abspath = ${abspath}"
echo "PWD = $PWD"
The Results
- the normal dirname $0 result
- the lsof method
- another attempt (found on google) which doesn't appear to work
- the cd/pwd method (my preferred)
- present directory for reference
~/temp$ ../temp.sh basename = temp.sh dirname = .. 0%%/* = .. LSOF = sh 731 krsmes 255r REG 14,3 734 20668453 /Volumes/MacData/Users/krsmes/temp.sh MY_PATH = /Volumes/MacData/Users/krsmes/temp.sh MY_ROOT = /Volumes/MacData/Users/krsmes script_dir_link = . script_dir = .. abspath = /Users/krsmes PWD = /Users/krsmes/temp
source material: http://hintsforums.macworld.com/archive/index.php/t-73839.html
ReplyDelete