When a script is run from a command line then the 0th parameter is the script's name. However, when a script is run via
source command, then the 0th parameter is a shell name. Weird, but true.
$ cat test.sh
echo "\$0 is $0"
$ bash test.sh
$0 is test.sh
$ source ./test.sh
$0 is bash
When sourcing, the $0 becomes current directory + "bash". In total, this is even stranger in total:
OdpowiedzUsuń$ cat script.sh
#! /bin/bash
readlink -f $0
$ ./script.sh
/tmp/script.sh
$ source ./script.sh
/tmp/bash
$ stat /tmp/bash
stat: cannot stat '/tmp/bash': No such file or directory
$ cd /proc/
$ source /tmp/script.sh
/proc/bash
Thanks for the comment. It is bizarre. :) I really hate such quirks, one has to become an expert in order to write reliable scripts.
OdpowiedzUsuńI don't think source should be interpreted as running a script, but more in-lining the script in the currently-running script. In light of that it makes sense that $0 would be bash. Also see example below:
OdpowiedzUsuń$ cat a.sh
echo \$0 is $0
$ cat b.sh
source a.sh
$ bash a.sh
$0 is a.sh
$ bash b.sh
$0 is b.sh