4

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)

Igor Chubin
  • 61,765
  • 13
  • 122
  • 144
Taha Jahangir
  • 4,774
  • 2
  • 42
  • 49

1 Answers1

3

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.

Igor Chubin
  • 61,765
  • 13
  • 122
  • 144
  • 2
    This is bash specific. I mentioned in question that I searching for a solution that works on bash/csh/zsh – Taha Jahangir Dec 08 '13 at 09:18
  • And note that I used `/bin/sh` as interpreter – Taha Jahangir Dec 08 '13 at 09:20
  • I've note in the answer that it will only work in bash. In bourne-shell it is impossible. – Igor Chubin Dec 08 '13 at 09:20
  • 1
    @TahaJahangir: You have written that you look for solution for tcsh/zsh/bash; I've provided you with it. My solution will work in bash/tcsh/zsh. – Igor Chubin Dec 08 '13 at 09:25
  • In bash We can use `${VAR:-DEFAULT}` construct to use another variable if $VAR is not defined, but this not works in tsch/zsh. Also $_ not works in `sh`!. Can you modify you solution to work on csh and bash, or sh? – Taha Jahangir Dec 08 '13 at 09:33
  • @TahaJahangir: I know, that `$_` will not work in Bourne shell. I've written it. As far as I know there are no way to find that name of included script in Bourne shell. – Igor Chubin Dec 08 '13 at 09:35
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/42730/discussion-between-taha-jahangir-and-igor-chubin) – Taha Jahangir Dec 08 '13 at 09:37