简体   繁体   English

我为什么不能在/ etc /中sudo回显一行?

[英]Why can't I sudo echo a line in /etc/?

I am on centos and I did sudo echo 'testline'>>/etc/test/test it said -bash: /etc/test/test: Permission denied 我在centos上并做了sudo echo 'testline'>>/etc/test/test它说-bash: /etc/test/test: Permission denied

However, when I do sudo vi /etc/test/test and insert testline and do :wq it writes out fine, why is this happening? 但是,当我执行sudo vi /etc/test/test并插入testline并执行:wq它写得很好,为什么会这样?

You need to wrap the whole statement (including the redirect) into a group so the sudo extends around it. 您需要将整个语句(包括重定向)包装到一个组中,以便sudo在其周围扩展。

sudo bash -c "echo 'testline' >> /etc/test/test"

Note: that, too, will fail if /etc/test doesn't exist yet. 注意:如果/etc/test还不存在,那也会失败。

The redirection is processed by the shell prior to running sudo , rather than being part of it. 重定向是在运行sudo之前由外壳处理的,而不是它的一部分。 Use tee instead so that sudo runs the process that actually opens the file for writing. 请改用tee以便sudo运行实际上打开文件进行写入的过程。

echo 'testline' | sudo tee -a /etc/test/test > /dev/null

这些人已经介绍过的相同一般解决方案的另一种语法:

echo "echo 'testline'>>/etc/test/test" | sudo su

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM