Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

run specific command without sudo inside script running with sudo bash

I have a bash script which I'm running with sudo: sudo NewScript

Inside the script, I have a git command which I don't want to run with sudo. Currently, since the entire script is run with sudo this command also runs with sudo and that's what I would like to suppress.

Is such thing possible or do I need to run the script without sudo and add sudo for every command inside the script other than the git command?

like image 533
Idanis Avatar asked Dec 28 '16 16:12

Idanis


People also ask

How do I run a command without sudo?

For any reasons, if you want to allow a user to run a certain command without the sudo password, you need to add that command in sudoers file. Let me show you an example. I want an user named sk to execute mkdir command without giving the sudo password.

How do I run a command as a root in shell script?

To give root privileges to a user while executing a shell script, we can use the sudo bash command with the shebang. This will run the shell script as a root user. Example: #!/usr/bin/sudo bash ....

Can I use sudo in a script?

Within a script, before a command that requires elevated privilege, you check the UID (and or EUID ) of the current user. If it isn't 0 and root privileges are needed, then you can use sudo to execute the command (or start a separate subshell if more than a simple command is involved).


1 Answers

Note that sudo runs programs as a different user, not necessarily as root; root is just the default. So your goal is probably not to run your specific git command without sudo, but rather to run it as a different user than the rest.

If you want you git command to be run by a hard-coded user the_user, just put

sudo -u the_user <your git command>

in your script (this will not prompt you for your password when the script is run as root).

If you don't know the user in advance but rather want the git command to be run by whoever called sudo newScript use

sudo -u $SUDO_USER <your git command>

instead (thanks to @thatotherguy for that hint).

like image 69
Dreamer Avatar answered Oct 22 '22 03:10

Dreamer