Sod Almighty Sod Almighty - 3 months ago 9
Bash Question

How to use output redirection with sudo?

I wish to write text from stdin to a file that is owned by root.

I'm doing this programmatically across an SSH connection - essentially from a script - so using a text editor is out of the question. There is no terminal. The process is entirely automated.

Given that [a] root elevation can be obtained via

sudo
, and [b] files can be written to using
cat
with redirection, I assumed the following would work:

ssh user@host sudo cat >the-file


Unfortunately, the redirection is applied to
sudo
, not to
cat
. How can I apply redirection to
cat
in this example?

Answer

The normal pattern to do this is:

ssh user@host 'cat | sudo tee the-file'

tee redirects output to a file and can be run with sudo.

If you want to mimic >> where the file is appended-to, use sudo tee -a.

You'll also need to be sure to quote your command as above, so that the pipe isn't interpreted by the local shell.

Edit

The tee command is part of POSIX, so you can rely on it existing.

To redirect Standard Error as well:

ssh user@host 'some_command 2>&1 | sudo tee output-file'
Comments