Using sudo on a Group of Commands

Problem

You are running as a regular user and need to sudo several commands at once, or you need to use redirection that applies to the commands and not to sudo.

Solution

Use sudo to run a subshell in which you may group your commands and use pipe-lines and redirection:

sudo bash -c 'command1 && command2 || command3'

This requires the ability to run a shell as root. If you can’t, have your system administrator write a quick script and add it to your sudo privilege specification.

Discussion

If you try something like sudo command1 && command2|| command3 you’ll find that command2 and command3 are running as you, not as root. That’s because sudo’s influence only extends to the first command and your shell is doing the redirection.

Note the use of the -c argument to bash, which causes it to just execute the given commands and exit. Without that you will just end up running a new interactive root shell, which is probably not what you wanted. But as noted above, with -c you are still running a (non-interactive) root shell, so you need to have the sudo rights to do that. Mac OS X and some Linux distributions, such as Ubuntu, actually disable the root user to encourage you to only log in as a normal user and sudo as needed (the Mac hides this better) for administration. If you are using an OS like that, or have rolled your own sudo setup, you should be fine. However, if you are running a locked-down environment, this recipe may not work for you.

To learn whether ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.