![当参数传递或不传递时,bash的第一个参数是不同的](https://linux22.com/image/73307/%E5%BD%93%E5%8F%82%E6%95%B0%E4%BC%A0%E9%80%92%E6%88%96%E4%B8%8D%E4%BC%A0%E9%80%92%E6%97%B6%EF%BC%8Cbash%E7%9A%84%E7%AC%AC%E4%B8%80%E4%B8%AA%E5%8F%82%E6%95%B0%E6%98%AF%E4%B8%8D%E5%90%8C%E7%9A%84.png)
有两种bash
用法:
$ bash -c 'echo $0'
bash
$bash -c 'echo $0' "text"
text
为什么在第一种情况下参数$0
保存程序名称,而在第二种情况下参数保存第一个参数?
答案1
根据bash
手册页:
-c If the -c option is present, then commands are read from the first non-option argument command_string. If there are argu‐ ments after the command_string, they are assigned to the positional parameters, starting with $0.
再往下:
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.
简而言之,$0
的行为根据 bash 的调用方式而变化。