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?
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.
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 ....
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).
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With