使用 sudo bash -c 'echo $myVariable' 回显变量 - bash 脚本

use*_*150 4 bash shell

我想将字符串回显到/etc/hosts文件中。该字符串存储在名为 的变量中$myString

当我运行以下代码时,回显为空:

finalString="Hello\nWorld"
sudo bash -c 'echo -e "$finalString"'
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Ign*_*ams 6

  1. 您不会将变量导出到环境中,以便子进程可以获取它。

  2. 你没有告诉我们sudo要保护环境。

\

finalString="Hello\nWorld"
export finalString
sudo -E bash -c 'echo -e "$finalString"'
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用当前的 shell 替代品:

finalString="Hello\nWorld"
sudo bash -c 'echo -e "'"$finalString"'"'
Run Code Online (Sandbox Code Playgroud)