sudo redirection

We are faced with a problem when trying to use redirection with sudo, as the second part of the command is not executed with root privileges.
sudo command > outputfile
<>—-root——<>—user—<>
The solution is to use;
‘sudo tee’ instead of the ‘>’ operator,
‘sudo tee -a’ instead of the ‘>>’ operator.
sudo command | sudo tee outputfile
<>—–root—–<>——-root——<>
The problem can be seen using a simple demonstration:

petur@laptop:/tmp$ sudo date > output
petur@laptop:/tmp$ ls -l
total 4
-rw-r--r-- 1 petur petur 30 2010-07-06 23:14 output
petur.petur is the owner of the output file.

petur@laptop:/tmp$ rm output


petur@laptop:/tmp$ sudo date | sudo tee output
Tue Jul 6 23:15:31 CEST 2010
petur@laptop:/tmp$ ls -l
total 4
-rw-r--r-- 1 root root 30 2010-07-06 23:15 output
root.root is the owner of the output file.

Leave a Reply