From Bash Manual
$0
Expands to the name of the shell or shell script. This is set at
shell initialization.If Bash is invoked with a file of commands (see Section 3.8 [Shell
Scripts], page 39),$0
is set to the name of that file.If Bash is started with the
-c
option (see Section 6.1 [Invoking
Bash], page 80), then$0
is set to the first argument after the
string to be executed, if one is present.Otherwise, it is set to the filename used to invoke Bash, as given by argument zero.
I understand the first two cases, but not the last one.
What do "otherwise" and "the filename used to invoke Bash" mean specifically?
Best Answer
Bash can be invoked in various ways, including directly using its executable (
/bin/bash
) or a link to it; this is often the case with/bin/sh
. "Otherwise" covers this case, and the filename used to invoke Bash is just that —bash
,sh
,/bin/sh
etc.Try it and you'll see:
bash
thenecho $0
printsbash
,/bin/bash
thenecho $0
prints/bin/bash
, etc.Arguably this also covers shebangs but perhaps that's the first case.