使用sudobash-c';echo$myVariable';-bash脚本
我想在/etc/hosts文件中回显一个字符串。该字符串存储在名为使用sudobash-c';echo$myVariable';-bash脚本,bash,shell,Bash,Shell,我想在/etc/hosts文件中回显一个字符串。该字符串存储在名为$myString的变量中 运行以下代码时,回显为空: finalString="Hello\nWorld" sudo bash -c 'echo -e "$finalString"' 我做错了什么 您没有将变量导出到环境中,以便子流程可以拾取它 你还没有告诉sudo保护环境 \ 或者,您可以使用当前的shell替换: finalString="Hello\nWorld" sudo bash -c 'echo -e "'"$fi
$myString
的变量中
运行以下代码时,回显为空:
finalString="Hello\nWorld"
sudo bash -c 'echo -e "$finalString"'
我做错了什么
finalString="Hello\nWorld"
sudo bash -c 'echo -e "'"$finalString"'"'
您可以这样做:
bash -c "echo -e '$finalString'"
i、 e使用双引号将参数传递给子shell,因此变量($finalString
)按预期展开(由当前shell展开)
尽管我建议不要将-e
标志与echo
一起使用。相反,您只需执行以下操作:
finalString="Hello
World"
也就是说:使用
export
使变量在子shell中可用。要将变量导出到环境中,只是“export finalString”吗?因为它仍然没有打印变量。@user2771150在sudo-->sudo-ebash-c'echo-E“$finalString”
中可能需要-E
。它们都“安全”吗?有“推荐”的方法吗?很抱歉我对bash脚本非常陌生。
finalString="Hello
World"