How to redirect command output using sudo

You have probably already noticed my favorite way to overcome sudo redirection issue, but if you haven't, then I will write it down here for further reference.

Try, for example, to clear /etc/issue file as regular user. You will encounter Permission denied error which is an expected behavior.

$ clear > /etc/issue
bash: /etc/issue: Permission denied

You can't just insert sudo at the beginning of the above-mentioned command as redirection will be executed with user rights, so the fact that clear command will be executed with root rights can be omitted in this example.

$ sudo clear > /etc/issue
bash: /etc/issue: Permission denied

To solve this issue you can simply use tee command.

$ clear | sudo tee /etc/issue

Additional tee examples

Append additional configuration directive.

$ echo GRUB_RECORDFAIL_TIMEOUT=20 | sudo tee -a /etc/default/grub

Write multi-line configuration.

$ cat << EOF | sudo tee /etc/network/interfaces
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet dhcp
EOF

Write to multiple files.

$ echo "Linux at home" | sudo tee /etc/issue /etc/issue.net

Simply store command output.

$ make | sudo tee /root/make.log

Store compressed data and preview it in parallel.

$ sudo find . -type f -exec sha1sum {} \; | tee >(gzip > /tmp/sha1sum.gz) | vim -

Store results depending on their state.

$ sudo netstat -tapn | tee >(grep LISTEN > tcp_listen.log) >(grep ESTABLISHED > tcp_established.log)
Milosz Galazka's Picture

About Milosz Galazka

Milosz is a system administrator working for a successful Polish company and a long time supporter of Free Software Foundation and Debian operating system.

Gdansk, Poland https://sleeplessbeastie.eu