[英]Echo variable using sudo bash -c 'echo $myVariable' - bash script
我想将一个字符串回显到/ etc / hosts文件中。 该字符串存储在名为$myString
的变量中。
当我运行以下代码时,echo为空:
finalString="Hello\nWorld"
sudo bash -c 'echo -e "$finalString"'
我究竟做错了什么?
您不是将变量导出到环境中,以便可以通过子进程获取它。
你没有告诉sudo
保护环境。
\\
finalString="Hello\nWorld"
export finalString
sudo -E bash -c 'echo -e "$finalString"'
或者,您可以使用当前的shell替换:
finalString="Hello\nWorld"
sudo bash -c 'echo -e "'"$finalString"'"'
你可以这样做:
bash -c "echo -e '$finalString'"
即使用双引号将参数传递给子shell,因此变量( $finalString
)按预期扩展(由当前shell)。
虽然我建议不要在echo
使用-e
标志。 相反,你可以这样做:
finalString="Hello
World"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.