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

标签 bash shell

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

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

finalString="Hello\nWorld"
sudo bash -c 'echo -e "$finalString"'

我做错了什么?

最佳答案

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

  2. 您还没有告诉 sudo 保护环境。

\

finalString="Hello\nWorld"
export finalString
sudo -E bash -c 'echo -e "$finalString"'

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

finalString="Hello\nWorld"
sudo bash -c 'echo -e "'"$finalString"'"'

关于bash - 使用 sudo bash -c 'echo $myVariable' 回显变量 - bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37004340/

相关文章:

linux - 使用 UNIX BASH 将文件复制到其他虚拟机

linux - 合并 awk 脚本的问题

bash - 捕获 perl 脚本内的 bash 输出值

linux - 在两个不同的目录中运行两个守护进程作业

linux - 仅针对错误消息自定义带有前缀的命令响应

Python 脚本在 bash 中有效,但在通过系统从 R 调用时无效

bash - Shell:连接到网站并访问字段

bash - IntelliJ 中的 zsh

python - 带有选项的 Sublime Text 构建系统

bash - 如何在 unix 中从当前时间减去 60 分钟