Permission denied when trying to append a file to

2020-02-16 08:25发布

This is the shell command that results in "Permission denied" when I'm trying to append the data in a file to another file with sudo:

sudo cat add_file >> /etc/file

The file at /etc/file is owned by root (i.e. me) and its permissions are rw-r--r--. Should I become root for a moment to make it work or is there a workaround for sudo?

6条回答
祖国的老花朵
2楼-- · 2020-02-16 08:57

Similar approach to @gniourf_gniourf answer, but using ex:

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

which is equivalent to vi/vim Ex-mode (-e).

This in-place edit example is simple, safe and convenient approach, because it doesn't use any shell piping, FIFOs or shell within the shell workarounds.

To boost performance for scripting purposes, consider using silence mode (-s).

查看更多
虎瘦雄心在
3楼-- · 2020-02-16 08:59

Run bash as sudo:

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

$ whoami;sudo bash -c "whoami";whoami
iiSeymour
root
iiSeymour
查看更多
萌系小妹纸
4楼-- · 2020-02-16 09:09

Try doing this instead :

sudo tee -a /etc/file < add_file

It's lighter than running bash or sh -c command

查看更多
爷的心禁止访问
5楼-- · 2020-02-16 09:10

A funny possibility is to use ed (the standard editor):

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

I know I won't get upvoted for this wonderful answer, but I wanted to include it here anyway (because it's funny). Done!

查看更多
冷血范
6楼-- · 2020-02-16 09:11

try

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

or

cat add_file | sudo tee -a /etc/file > /dev/null
查看更多
等我变得足够好
7楼-- · 2020-02-16 09:12

You are trying to write the result of the command sudo cat add_file to the file /etc/file. And apparently you don't have that right.

man sudo gives that example :

   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"

So you should try :

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

查看更多
登录 后发表回答