The $PWD
variable (which is also queried by pwd
command) will tell you current working directory where the shell script operates. However, finding where the script itself is located depends on couple factors.
If you are using bash
shell, you may use ${BASH_SOURCE[0]}
variable for the purpose of finding where the script runs, as shown by Dave Dopson:
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
In other cases, such as zsh
(unless in a function), ksh
, and POSIX /bin/sh
the $0
variable should be queried, probably with the use of dirname
command, or via parameter substitution. Note that this applies mostly to the top-level scripts that you execute.
However, sourced scripts can be a problem, if you're not using bash
and ${BASH_SOURCE[0]}
variable. According to Gilles's answer, location of sourced scripts is not available in general from within the script itself. The calling script will know the location, but the sourced script - won't. However, the cited answer by Gilles offers a few solutions. There are a few ways to portably determine if the script is sourced, however it seems the only benefit of that is to determine that script location is not available.