尝试使用sudo将文件附加到root拥有的文件时,权限被拒绝

时间:2012-12-08 15:22:53

标签: linux bash shell command-line sudo

当我尝试使用sudo将文件中的数据附加到另一个文件时,这是导致“权限被拒绝”的shell命令:

sudo cat add_file >> /etc/file

/etc/file处的文件归root所有(即我),其权限为rw-r--r--。我应该暂时root使其成功吗?还是sudo有解决方法?

6 个答案:

答案 0 :(得分:62)

bash

运行sudo
$ sudo bash -c "cat add_file >> /etc/file"

$ whoami;sudo bash -c "whoami";whoami
iiSeymour
root
iiSeymour

答案 1 :(得分:25)

尝试这样做:

sudo tee -a /etc/file < add_file

它比运行bash或sh -c command

更轻

答案 2 :(得分:9)

一个有趣的可能性是使用ed(标准编辑器):

sudo ed -s /etc/file <<< $'r add_file\nwq'

我知道我不会因为这个精彩的回答而投票,但我想把它包含在这里(因为它很有趣)。完成!

答案 3 :(得分:5)

您正在尝试将命令sudo cat add_file的结果写入文件/ etc / file。显然你没有这个权利。

man sudo给出了这个例子:

   To make a usage listing of the directories in the /home partition.  Note
   that this runs the commands in a sub-shell to make the cd and file
   redirection work.

    $ sudo sh -c "cd /home ; du -s * | sort -rn > USAGE"

所以你应该尝试:

sudo sh -c "cat add_file >> /etc/file"

答案 4 :(得分:1)

@gniourf_gniourf答案的类似方法,但使用ex

sudo ex +"r in.txt" -cwq out.txt

相当于vi / vim前模式(-e)。

这个就地编辑示例是简单,安全和方便的方法,因为它在shell解决方法中没有使用任何shell管道,FIFO或shell。

为了提高脚本编写性能,请考虑使用静默模式(-s)。

答案 5 :(得分:-2)

尝试

sudo bash -c 'cat add_file >> /etc/file'

cat add_file | sudo tee -a /etc/file > /dev/null
相关问题