Search code examples
bashshellzshtcsh

How to find script directory in an included shell script


We now to find the directory of a shell script using dirname and $0, but this doesn't work when the script is inluded in another script.

Suppose two files first.sh and second.sh:

/tmp/first.sh :

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

/tmp/test/second.sh :

#!/bin/sh
echo $0

by running first.sh the second script also prints first.sh. How the code in second.sh can find the directory of itself? (Searching for a solution that works on bash/csh/zsh)


Solution

  • There are no solution that will work equally good in all flavours of shells.

    In bash you 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
    

    As you can see, the script prints the name of 2.sh, although you start /tmp/1.sh, that includes 2.sh with the source command.

    I must note, that this solution will work only in bash. In Bourne-shell (/bin/sh) it is impossible.

    In csh/tcsh/zsh you can use $_ instead of BASH_SOURCE.