45

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

sudo cat add_file >> /etc/file

at 的文件/etc/fileroot(即我)所有,其权限为rw-r--r--. 我应该root暂时让它工作还是有解决方法sudo

4

6 回答 6

68

运行bashsudo

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

$ whoami;sudo bash -c "whoami";whoami
iiSeymour
root
iiSeymour
于 2012-12-08T15:25:49.020 回答
27

尝试这样做:

sudo tee -a /etc/file < add_file

它比运行 bash 或sh -c command

于 2012-12-08T15:24:44.777 回答
9

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

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

我知道我不会因为这个精彩的答案而获得投票,但我还是想把它包括在这里(因为它很有趣)。完毕!

于 2012-12-08T15:42:58.083 回答
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"

于 2012-12-08T15:32:57.540 回答
1

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

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

相当于 vi/ vimEx-mode ( -e)。

这个就地编辑示例是简单、安全和方便的方法,因为它不使用任何 shell 管道、FIFO 或 shell 变通方法中的 shell。

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

于 2015-05-25T11:18:22.660 回答
-2

尝试

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

或者

cat add_file | sudo tee -a /etc/file > /dev/null
于 2014-02-27T21:19:11.183 回答