Permission denied when trying to append a file to

2020-02-16 08:52发布

问题:


Want to improve this question? Update the question so it's on-topic for Stack Overflow.

Closed 4 years ago.

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?

回答1:

Run bash as sudo:

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

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


回答2:

Try doing this instead :

sudo tee -a /etc/file < add_file

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



回答3:

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!



回答4:

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"



回答5:

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).



回答6:

try

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

or

cat add_file | sudo tee -a /etc/file > /dev/null