Unix shell script find out which directory the script file resides? Unix shell script find out which directory the script file resides? unix unix

Unix shell script find out which directory the script file resides?


In Bash, you should get what you need like this:

#!/usr/bin/env bashBASEDIR=$(dirname "$0")echo "$BASEDIR"


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")"

Bash Reference Manual, 5.2 Bash Variables