我想将字符串回显到/etc/hosts文件中。该字符串存储在名为 的变量中$myString
。
当我运行以下代码时,回显为空:
finalString="Hello\nWorld"
sudo bash -c 'echo -e "$finalString"'
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
您不会将变量导出到环境中,以便子进程可以获取它。
你没有告诉我们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)