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)
There are no solution that will work equally good in all flavours of shells.
In
bashyou can useBASH_SOURCE:Example:
As you can see, the script prints the name of
2.sh, although you start/tmp/1.sh, that includes2.shwith thesourcecommand.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 ofBASH_SOURCE.