How to Echo Text to root Owned File Using sudo

Sometimes it is desired to echo text to a root owned file using sudo. The following will not work:

$ sudo echo "my text" > /tmp/testfile

In the above example you are echoing “my text” as root but after the redirect it is no longer the root account sending the output to /tmp/testfile so the file will be owned by your user account and not root.

Instead execute the above command using the following method:

$ echo "my text" | sudo tee /tmp/testfile

In the above example you echo “my text” as your user account which is then piped to root executed tee which then outputs to the file. The file will now be owned as root.

Likewise you can also append to a root owned file with the following command format:

$ echo "appended text" | sudo tee -a /tmp/testfile

This just uses the -a ( append ) option of tee which is still being executed as root.

You may also like...