Rerouting stdout to a documents you do not have write permission on

When you try to change a documents without having write permissions on it, you get a mistake:

> touch /tmp/foo && sudo chown root /tmp/foo
> echo test > /tmp/foo
zsh: permission denied: /tmp/foo

Sudoing does not aid, due to the fact that it runs the command as origin, yet the shell takes care of rerouting stdout and also opens up the documents as you anyhow:

> sudo echo test > /tmp/foo
zsh: permission denied: /tmp/foo

Exists a very easy means to reroute stdout to a documents you do not have permission to contact, besides opening up a shell as origin and also adjusting the documents in this way?

> sudo su
# echo test > /tmp/foo
0
2019-05-04 03:53:34
Source Share
Answers: 3

Yes, making use of tee. So echo test > /tmp/foo comes to be

echo test | sudo tee /tmp/foo

You can additionally add (>>)

echo test | sudo tee -a /tmp/foo
0
2019-05-08 01:42:13
Source

tee is possibly the most effective selection, yet relying on your scenario something similar to this might suffice :

sudo sh -c 'echo test > /tmp/foo'
0
2019-05-07 18:50:15
Source

To change the web content of the documents with the result of echo (like the > shell redirection driver ).

echo test | sudo dd of=/tmp/foo

To write right into the documents (at the start, though you can make use of seek to result at various offsets ) without truncating (like the 1<> Bourne shell driver ) :

echo test | sudo dd of=/tmp/foo conv=notrunc

To add to the documents (like >> ), with GNU dd :

echo test | sudo dd of=/tmp/foo oflag=append conv=notrunc

See additionally GNU dd's conv=excl to stay clear of belting an existing documents (like with set -o noclobber in POSIX coverings ) and also conv=nocreat for the contrary (only upgrade an existing documents ).

0
2019-05-07 18:46:05
Source