Sod Almighty Sod Almighty - 2 months ago 5x
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

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

ssh user@host sudo cat >the-file

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


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.


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'