15

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?

Inian
  • 80,270
  • 14
  • 142
  • 161
Idanis
  • 1,918
  • 6
  • 38
  • 69
  • 2
    When you run a script with `sudo`, the script is run basically as if it was run by the root user. So the only solution I can think of is to run your git command with permissions of a specific user like so: `sudo -S [username] [git command]` – Dunno Dec 28 '16 at 16:36
  • If the latter approach, if `sudo` required a password, you will be prompted for password for all such commands. – Inian Dec 28 '16 at 16:36

2 Answers2

11

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).

Dreamer
  • 1,139
  • 9
  • 18
4

One approach to use is switch to normal user privileges using su and run it dynamically than actually changing the access.

Run the git commands with the normal $USER privileges inside the script.

su - "$USER" -c "git_command1; git_command2;"

The -c flag for passing commands to the shell, according to man su page,

-c, --command=command Pass command to the shell with the -c option.

Inian
  • 80,270
  • 14
  • 142
  • 161