Welcome, this is an Innovations Tech Tip. In this tip we’re going to cover how to run a command sequence, such as a pipeline, using
sudo which is sometimes also pronounced “pseudo”. It may be tempting to think of the “su” in
sudo as standing for “super user” since, especially if you’re an Ubuntu user, you normally use
sudo to execute things as root. Something that may surprise you though is that you can use the
-u option of
sudo to specify a user to run the command as. This is assuming that you have the proper privileges. Have a look at the
sudo man and info pages for more interesting options.
Now, if you’ve ever tried to use
sudo to run a command sequence such as a pipeline, where each step required superuser priveleges, you probably got a
Permission denied error. This is because
sudo only applies to the first command in the sequence and not the others. There are multiple ways to handle this, but there are two that stand out to me. First, you can use
sudo to start a shell (such as
bash) with root priveleges, and then give that shell the command string. This can be done using the
-c option of
bash. To illustrate how this works, I’ll start out using
sudo to run
cat on a file that I created in the
/root directory that I normally wouldn’t have access to.
$ cat /root/example.txt cat: /root/example.txt: Permission denied $ sudo cat /root/example.txt [sudo] password for jwright: You won't see this text without sudo.
If I try to use
sudo with a pipeline to make a compressed backup of the
/root/example.txt file, I again get the
Permission denied error.
$ sudo cat /root/example.txt | gzip > /root/example.gz -bash: /root/example.gz: Permission denied
Notice that it’s the second command (the
gzip command) in the pipeline that causes the error. That’s where our technique of using
bash with the
-c option comes in.
$ sudo bash -c 'cat /root/example.txt | gzip > /root/example.gz' $ sudo ls /root/example.gz /root/example.gz
We can see form the
ls command’s output that the compressed file creation succeeded.
The second method is similar to the first in that we’re passing a command string to
bash, but we’re doing it in a pipeline via
$ sudo rm /root/example.gz $ echo "cat /root/example.txt | gzip > /root/example.gz" | sudo bash $ sudo ls /root/example.gz /root/example.gz
Either method works, it’s just a matter of personal preference on which one to use.
That concludes this Tech Tip. Have a look at innovationsts.com for other tips, tricks, how-tos, and service offerings available from Innovations Technology Solutions. Thanks, and stay tuned for more quick tips from Innovations.