Bash – Why does `bash -c ‘echo $0 ‘ ` output “bash”

bash

$ bash -c 'echo $0 ' foo 
foo

$ bash -c 'echo $0 '  
bash

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.

What does "otherwise" mean?

What cases does it include?

Does it include the case when bash is started with -c without any "argument after the string to be executed"?

I expected bash -c 'echo $0 ' not to output anything, according to the second case in the quote, but it outputs bash.

Thanks.

Best Answer

The documentation you quote gives three cases:

If bash is invoked with a file of commands, $0 is set to the name of that file.

(case 1)

If bash is started with the -c option, then $0 is set to the first argument after the string to be executed, if one is present.

(case 2; note the two "if"s, which must both be satisfied in this case)

Otherwise, it is set to the filename used to invoke bash, as given by argument zero.

(case 3).

The "otherwise" clause covers any situation which isn't covered by cases 1 and 2: bash isn't invoked with a file of commands, and bash isn't started with the -c option, or it's started with the -c option but without any argument after the string to be executed.

So yes, it includes the case where Bash is started with -c without any argument after the string to be executed. It also includes the basic echo $0 case when run from an interactive shell, since the interactive shell was most likely started without either a file of commands or a -c option.