rick
rick

Reputation: 1125

sudo for single command in bash script

This may be a stupid question.

I have a script that I want to be portable between Mac OS X and a Linux box I use. In OS X, a command in the script requires sudo, where on the Linux box, it does not.

Long story short, how does one run one command in a script with sudo, while then removing the elevated privileges for the rest of the script?

I have tried to use

su -

and

su -c

but they both seem to error out. (They say "sorry" and move on, I assume because it is trying to run as root and root does not have a password).

I know there has to be a silly and easy way to do this, what does everyone suggest?

Upvotes: 8

Views: 19578

Answers (3)

sehe
sehe

Reputation: 393934

You can 'revoke' the sudo permission (actually: close the sudo time window early) by doing:

sudo -k

Also, you can configure sudo to only allow elevated permissions on certain commands, or even to impersonate non-root for specific commands. See man sudoers. The examples section makes it exceedingly clear that there is virtually no limit to the configurability of sudo (roles, hosts, commands, allow escaping, allow sudo target users, exceptions to allowed things, password less authorization etc etc).

Hopefully an interesting example in your context:

The user fred can run commands as any user in the DB Runas_Alias (oracle or sybase) without giving a password.

   fred           ALL = (DB) NOPASSWD: ALL

If you can't / don't really want to meddle with /etc/sudoers (visudo!) then I suggest using something like

{
     trap "sudo -k" EXIT INT QUIT TERM
     sudo ls # whatever
}

Upvotes: 7

Gordon Davisson
Gordon Davisson

Reputation: 126088

Use sudo without su:

#!/bin/bash
whoami  # Runs under your regular account
sudo whoami  # Runs as root
whoami  # Runs under your regular account again

Here's the output when I run it:

$ ./sudotest
gordon
Password:
root
gordon

Upvotes: 0

Adam Rosenfield
Adam Rosenfield

Reputation: 400672

Try sudo su instead of su to change back to a regular user.

Upvotes: 0

Related Questions