Background:

When developing scripts, it is sometimes necessary to determine the absolute location of the script within the script, so that relative paths may be defined. For example, if a script writes logs and data files to different directories relative to the location of the script, you need to determine the location of the script, irrespective of where the script is installed or from where it’s executed. Of course, you can hard code this value in the script, but that’s a dirty solution because you’ll need to change the variable whenever you change the location of the script.

 

Implementation:

(1) UNIX Shell:

if [ -n "`dirname $0 | grep '^/'`" ]; then
   SCRIPT_LOCATION=`dirname $0`
elif [ -n "`dirname $0 | grep '^..'`" ]; then
     cd `dirname $0`
     SCRIPT_LOCATION=$PWD
     cd – > /dev/null
else
     SCRIPT_LOCATION=`echo ${PWD}/\`dirname $0\` | sed ’s#\/\.$##g’`
fi

(2) Python

import sys
import os.path
from os import *
dirloc = os.path.dirname(sys.argv[0])
curdir = os.getcwd()
if dirloc.startswith("/"):
   SCRIPT_LOCATION = dirloc
elif dirloc.startswith(".."):
     os.chdir(dirloc)
     SCRIPT_LOCATION =  os.getcwd()
     os.chdir(curdir)
else:
     _SCRIPT_LOCATION = curdir + "/" + dirloc
     SCRIPT_LOCATION = _SCRIPT_LOCATION.rstrip("/.")
print SCRIPT_LOCATION 

Both implementations above are based on the assumption that a script may be executed in any of the following 3 ways only:

(1) From anywhere within the directory hierarchy , using the absolute path (beginning with ‘/’)

(2) From anywhere below the directory containing the script, within the directory hierarchy (beginning with ‘../’)

(3) From anywhere above the directory containing the script, within the directory hierarchy (beginning with ‘./’)

 


NOTE:

(1) The How-To above describes a successful method of implementation. It may or may not be the best method of implementation. If you know of a better implementation or spot an error in the implementation above, kindly make readers aware via comments on this post.

(2) Your rating of this post will be much appreciated. 


VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)