Petr Kozelka

bash script aware of its location for various types of invocation

29 November 2008 -

When writing a bash script launching a tool used directly on commandline, it is often convenient for the user to have various ways of invocation.
It is not a problem with trivial scripts, but those who need to access files with known location relative to the script, there are little troubles.
First, the script needs to determine its own absolute location on filesystem - because the user can "stay" in any directory. The user can also invoke it directly, using relative or absolute path; and finally, user can invoke a symlink pointing to it, again using relative or absolute path.
Following snippet shows how to handle such cases:


#!/bin/bash
D=${0%/*}
F=$( find $0 -printf %l )
if [ -z "$F" ]; then
   # it is not symlink
   case "$0" in
   /*) F=$0;;
   *) F=$PWD/$0
   esac
else
   # it is symlink
   case "$F" in
   /*);;
   *) F="$D/$F";;
   esac
fi
# now F=absolute path here
F=${F//\/\.\///}
D="${F%/*}"
# now F contains the script's pathname,
# D contains its containing directory

Fork me on GitHub
Fork me on GitHub