Unix shell script find out which directory the script file resides?
The original post contains the solution (ignore the responses, they don't add anything useful). The interesting work is done by the mentioned unix command readlink
with option -f
. Works when the script is called by an absolute as well as by a relative path.
For bash, sh, ksh:
#!/bin/bash # Absolute path to this script, e.g. /home/user/bin/foo.shSCRIPT=$(readlink -f "$0")# Absolute path this script is in, thus /home/user/binSCRIPTPATH=$(dirname "$SCRIPT")echo $SCRIPTPATH
For tcsh, csh:
#!/bin/tcsh# Absolute path to this script, e.g. /home/user/bin/foo.cshset SCRIPT=`readlink -f "$0"`# Absolute path this script is in, thus /home/user/binset SCRIPTPATH=`dirname "$SCRIPT"`echo $SCRIPTPATH
See also: https://stackoverflow.com/a/246128/59087
An earlier comment on an answer said it, but it is easy to miss among all the other answers.
When using bash:
echo this file: "$BASH_SOURCE"echo this dir: "$(dirname "$BASH_SOURCE")"