Finding the Absolute Path of a Bash Script

This seems to be one that a lot of people want to know how to do (I was one of them). In searching the internets I found a lot of suggestions to use the readline external command. I need to have the script that uses this work on Linux and AIX though, which means readline and many other external commands will not be available to me. Here’s how it can be done in bash

#
# Determines the absolute path to the running script. This is useful for
# needing to muck around in the running directory when the script has been
# called using a relative path
#
getScriptAbsolutePath() {
  if [[ ${0:0:1} == '/' ]]; then
    # If the script was called absolutely
    absPath=${0}
  else
    # If the script was called relatively, strip the . off the front
    script=`echo ${0} | sed 's/\.\?\(.*\)$/\1/'`
    absPath="$(pwd)/${script}"
  fi
  # Strip the script filename off the end
  absPath=`echo ${absPath} | sed 's/\(.*\/\).*\$/\1/'`
}

So what we do here is start with two variables: The working directory (output of pwd), and command used to call the script ($0). The command used to call the script could be anything like

  • ./blah.sh

  • ./scripts/blah/blah.sh

  • /usr/local/res/scripts/blah/blah.sh

If argument 0 starts with a / (such as /usr/local/res/scripts/blah/blah.sh), the script was called using an absolute path, so we can just use $0 as our absolute path once we strip the script name off the end.

If otherwise, the script was called using a relative path and $0 needs to be appended to the output of pwd and to get the absolute path. Using sed, we strip off the leading period if it exists as well as the script filename.

Category:Linux Category:Bash Category:Scripting