关于非交互模式下 bash 行为的问题

Tho*_*zic 2 command-line bash

我基本上需要理解以下行为:

$ echo $SHELL
/bin/bash
$ bash -c echo $SHELL
Run Code Online (Sandbox Code Playgroud)

bash -c echo $SHELL产生空白输出,这让我很困惑,因为我希望设置 SHELL。对于 $BASH_VERSION 也是如此。

谁可以给我解释一下这个?

谢谢你的时间!

ste*_*ver 6

man bash

\n
   -c        If the -c option is present, then commands are read from  the\n             first non-option argument command_string.  If there are argu\xe2\x80\x90\n             ments after the command_string, the  first  argument  is  as\xe2\x80\x90\n             signed  to $0 and any remaining arguments are assigned to the\n             positional parameters.\n
Run Code Online (Sandbox Code Playgroud)\n

在 中bash -c echo $SHELL“第一个非选项参数”echo,而$SHELL由当前的交互式 shell 扩展并bash作为位置参数传递给$0。由于本身echo没有参数,因此打印一个空字符串。同时,设置为但被忽略。bash -c echo$0/bin/bash

\n

根据您想要做什么,您可以这样做

\n
bash -c 'echo $SHELL'\n
Run Code Online (Sandbox Code Playgroud)\n

echo $SHELL作为command_string传递到非交互式 bash shell(输出非交互式 shell 的值$SHELL),或者

\n
bash -c 'echo $0' $SHELL\n
Run Code Online (Sandbox Code Playgroud)\n

它将交互式 shell(的扩展)传递$SHELL给非交互式 bash shell $0,然后回显其值。

\n