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 you may use sudo and what you are and are not allowed to do, use sudo -l. Almost any other use of sudo will probably trigger a security message to your administrator tattling on you. You can try using sudo sudo-V | less as a regular user or just sudo -V | less if you are already root to get a lot of information about how sudo is compiled and configured on your system.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.226.121