Using sudo and redirecting output to a file

2014-02-04

Sudo is a cool tool to have under your belt.

 I have heard excuses for not using sudo so many times, that if I was given a penny every time I would at least be able to buy myself a coffee. At Starbucks. This behavior usually ends up with an anonymous user account with a very poor password, often shared between way too many people. I've heard:

And lastly:

Almost... I have to admit, it took me some time to figure that one out. And until then, I took it as a good excuse for doing a "sudo su -". Here is a simple example: you would like to transform the output from one command and store it in a file, as root, in a directory where you have no permission to write.

Example:

USERNAME@MYHOSTNAME:/var $sudo cat /etc/shadow | cut -d":" -f 1 > /var/test.file
-bash: /var/test.file: Permission denied

This is because both the redirection (the | and > signs) will be parsed by your shell, which is you. Both the "cut" command, and the redirection into /var/test.file will be executed as yourself, not root.

The solution is simple. And it is easy. Just run the whole thing using "sh -c", use tee, or use sponge. It is that easy.

USERNAME@MYHOSTNAME:/var $sudo sh -c "cat /etc/shadow | cut -d":" -f 1 > /var/test.file"
USERNAME@MYHOSTNAME:/var $sudo cat /etc/shadow | cut -d":" -f 1 | sudo tee /var/test.file"
USERNAME@MYHOSTNAME:/var $sudo cat /etc/shadow | cut -d":" -f 1 | sudo sponge /var/test.file"
USERNAME@MYHOSTNAME:/var $ls -la /var/test.file
-rw-r--r-- 1 root root 156 Jan 30 18:37 /var/test.file

One excuse less for not using sudo.  Rock on!