使用 --rcfile 和 -c 在新的 bash shell 中运行命令

Wil*_*ill 12 bash

我正在运行以下命令并希望它会返回 me BAR,因为我创建的新 shell 将首先运行 .mybashrc ,它$FOOecho $FOO执行之前设置。

bash --rcfile .mybashrc -c 'echo $FOO'
Run Code Online (Sandbox Code Playgroud)

.mybashrc:

export FOO="BAR"
Run Code Online (Sandbox Code Playgroud)

然而结果是空的。出了什么问题?

dg9*_*g99 13

默认情况下,非交互式bash执行不会加载初始化文件,例如.bashrc或您的--rcfile选项的目标。如man页面所述:

An interactive shell is one started without non-option arguments and without
the -c option whose standard input and error are both connected to terminals
... or one started with the -i option.
Run Code Online (Sandbox Code Playgroud)

因此,您可以通过强制bash充当交互式 shell来获得所需的行为-i

bash --rcfile .mybashrc -ci 'echo $FOO'
Run Code Online (Sandbox Code Playgroud)

  • @z0r 非交互式、非登录的 `bash` shell 应该执行 `$BASH_ENV` 中指定的文件的内容。 (3认同)