Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash -c has different argument semantics ($1 becomes $0!)

Tags:

bash

$ 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.

like image 569
Steven Lu Avatar asked Jun 22 '13 17:06

Steven Lu


1 Answers

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.

like image 117
hek2mgl Avatar answered Nov 03 '22 07:11

hek2mgl