当参数传递或不传递时,bash的第一个参数是不同的

当参数传递或不传递时,bash的第一个参数是不同的

有两种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 的调用方式而变化。

相关内容