How to find script directory in included shell script

Now we will find the script shell directory with dirnameand $0, but this will not work if the script is included in another script.

Suppose two files first.shand second.sh:

/tmp/first.sh:

#!/bin/sh
. "/tmp/test/second.sh"

/tmp/test/second.sh:

#!/bin/sh
echo $0

running the first.shsecond script will also print first.sh. How can code in second.shfind a directory of itself? (Finding a solution that works on bash / csh / zsh)

+4
source share
1 answer

There is no solution that will work equally well in all shell options.

In bashyou can use BASH_SOURCE:

$(dirname "$BASH_SOURCE")

Example:

$ cat /tmp/1.sh
. /tmp/sub/2.sh
$ cat /tmp/sub/2.sh
echo $BASH_SOURCE
$ bash /tmp/1.sh 
/tmp/sub/2.sh

, script 2.sh, /tmp/1.sh, 2.sh source.

, bash. Bourne-shell (/bin/sh) .

csh/tcsh/zsh $_ BASH_SOURCE.

+3

All Articles