如何解决尝试 echo 到文件时的权限被拒绝错误
问题:
你试图将字符串 echo 到只有 root 可访问的文件中,例如:
sudo_echo_example.sh
sudo echo "foo" > /etc/my.cnf但你只看到此错误消息:
sudo_echo_error.txt
-bash: /etc/my.cnf: Permission denied解决方案
使用 tee 代替(这也会将字符串 echo 到 stdout)
sudo_tee_example.sh
echo "foo" | sudo tee /etc/my.cfg # 覆盖:等效于 echo "foo" > /etc/my.cnf
echo "foo" | sudo tee -a /etc/my.cfg # 追加:等效于 echo "foo" >> /etc/my.cnf错误消息的原因是虽然 echo 使用 sudo 执行,但 >> /etc/my.cnf 以普通用户(非 root)身份运行。
另一种方法是作为 sudo 运行子 shell:
sudo_bash_subshell.sh
sudo bash -c 'echo "foo" > /etc/my.cnf'但这有几个注意事项,例如与转义相关,所以我通常不推荐这种方法。
Check out similar posts by category:
Linux
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow