2011-09-14

Bash Full Path to Script File

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

The_Script.png
#!/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

media_1316040951536.png
  1. the normal dirname $0 result
  2. the lsof method
  3. another attempt (found on google) which doesn't appear to work
  4. the cd/pwd method (my preferred)
  5. 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

1 comment:

  1. source material: http://hintsforums.macworld.com/archive/index.php/t-73839.html

    ReplyDelete