Note: For a POSIX-compliant solution, see this answer.
${BASH_SOURCE[0]}
(or, more simply, $BASH_SOURCE
[1] ) contains the (potentially relative) path of the containing script in all invocation scenarios, notably also when the script is sourced, which is not true for $0
.
Furthermore, as Charles Duffy points out, $0
can be set to an arbitrary value by the caller.
On the flip side, $BASH_SOURCE
can be empty, if no named file is involved; e.g.:echo 'echo "[$BASH_SOURCE]"' | bash
The following example illustrates this:
Script foo
:
#!/bin/bash
echo "[$0] vs. [${BASH_SOURCE[0]}]"
$ bash ./foo
[./foo] vs. [./foo]
$ ./foo
[./foo] vs. [./foo]
$ . ./foo
[bash] vs. [./foo]
$0
is part of the POSIX shell specification, whereas $BASH_SOURCE
, as the name suggests, is Bash-specific.
Copied from: https://stackoverflow.com/questions/35006457/choosing-between-0-and-bash-source