假设我在这里有以下文档(用于在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实例中,变量显然不存在。
答案 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}"