You have probably already noticed my favorite way to overcome the 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 a regular user. You will encounter Permission denied error, which is 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 performed with user rights.

$ 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 a 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)
ko-fi