为什么我的 shell (sh) 命令模式下的变量没有导出?

Why is my shell (sh) variable in command mode not exported?

如果我 运行 像这样的 shell 命令,我导出的变量是不可见的。

sh -c "export x=100; echo x is $x"

我希望它输出 "x is 100" 但它只是说 "x is "。如果我 运行 这是在交互模式下,它会像预期的那样工作。

我的 shell 版本是:GNU bash,版本 3.2.51(1)-release (x86_64-suse-linux-gnu)

$x 由当前 shell 解释,而不是您开始的 sh shell。

用反斜杠转义:

sh -c "export x=100; echo x is $x"

或者使用单引号来防止shell解释变量:

sh -c 'export x=100; echo x is $x'