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

How can a Bash variable be used in a string passed to Bash?

假设我有以下文档(用于在 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

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

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

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

text 变量在新的 bash 环境中不再定义,这就是它失败的原因。

下面这个命令已经测试成功,试一试:

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

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

sudo bash -c 'printf "%s\n" "[=10=]" > /path/to/output' "$text"