$ bash -c 'echo "0 is $0 1 is $1"' abc def
0 is abc 1 is def
$ echo 'echo "0 is $0 1 is $1"' > bashtest
$ bash bashtest abc def
0 is bashtest 1 is abc
The second run is equivalent to if I turned bash test into a shellscript with the shebang and then ran it directly...
Basically I'm wondering why abc isn't always $1
. It becomes $0
when run with bash -c
.
I also didn't know this. But the man page mentions it:
-c string: If the -c option is present, then commands are read from string. If there are arguments after the string, they are assigned to the positional parameters, starting with $0.
The ARGUMENTS
section has an even more detailed explanation:
ARGUMENTS
If arguments remain after option processing, and neither the -c nor the -s option has been supplied, the first argument is assumed to be the name of a file containing shell commands. If bash is invoked in this fashion, $0 is set to the name of the file, and the positional parame‐ ters are set to the remaining arguments. Bash reads and executes com‐ mands from this file, then exits. Bash's exit status is the exit sta‐ tus of the last command executed in the script. If no commands are executed, the exit status is 0. An attempt is first made to open the file in the current directory, and, if no file is found, then the shell searches the directories in PATH for the script.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With