Sudo for single command in bash script

This may be a dumb question.

I have a script that I want to be portable between Mac OS X and the Linux box used. In OS X, the command in the script requires sudo , where in a Linux box this is not the case.

In short, how to run one command in a script with sudo and then remove elevated privileges for the rest of the script?

I tried to use

 su - 

and

 su -c 

but both of them seem to be mistakes. (They say "sorry" and move on, I suppose, because it tries to work as root and root does not have a password).

I know that there must be a stupid and easy way to do this that everyone offers?

+8
scripting bash sudo
source share
3 answers

You can β€œinvalidate” sudo permission (actually: close the sudo time window early):

 sudo -k 

In addition, you can configure sudo only for permissions to certain commands, or even to impersonate non-root for certain commands. See man sudoers . The examples section makes it extremely obvious that there are practically no restrictions on the configurability of sudo (roles, hosts, commands, screening permission, allow suudo users, exceptions for allowed things, password is less than authorization, etc. Etc.).).

Hope an interesting example in your context:

User fred can run commands like any user in DB Runas_Alias ​​(oracle or sybase) without specifying a password.

  fred ALL = (DB) NOPASSWD: ALL 

If you cannot / do not want to interfere with / etc / sudoers (visudo!), Then I suggest using something like

 { trap "sudo -k" EXIT INT QUIT TERM sudo ls # whatever } 
+6
source share

Try sudo su instead of su to return to regular user.

0
source share

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 is the output at startup:

 $ ./sudotest gordon Password: root gordon 
0
source share

All Articles