如何在传递给Bash的字符串中使用Bash变量?

时间:2016-04-18 09:02:25

标签: bash variables echo sudo

假设我在这里有以下文档(用于在Ubuntu中启用休眠):

IFS= read -d '' text << "EOF"
[Re-enable hibernate by default in upower]
Identity=unix-user:*
Action=org.freedesktop.upower.hibernate
ResultActive=yes

[Re-enable hibernate by default in logind]
Identity=unix-user:*
Action=org.freedesktop.login1.hibernate
ResultActive=yes
EOF

我可以通过以下方式将此文本存储在受保护的文件中:

echo "${text}" | sudo tee /etc/polkit-1/localauthority/50-local.d/com.ubuntu.enable-hibernate.pkla

如何在命令字符串(使用重定向运算符)中使用Bash变量进行类似的操作传递给在root下运行的Bash?

sudo bash -c 'echo "${text}" > /etc/polkit-1/localauthority/50-local.d/com.ubuntu.enable-hibernate.pkla'

在新的Bash实例中,变量显然不存在。

2 个答案:

答案 0 :(得分:1)

一种选择是将变量作为参数传递,如下所示:

sudo bash -c 'printf "%s\n" "$0" > /path/to/output' "$text"

答案 1 :(得分:0)

新的text环境中不再定义

bash变量,这就是它失败的原因。

以下命令已经过测试,请试一试:

 sudo bash -c 'cat  > /etc/polkit-1/localauthority/50-local.d/com.ubuntu.enable-hibernate.pkla' <<<"${text}"