16

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?

2
  • 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] Commented Dec 28, 2016 at 16:36
  • If the latter approach, if sudo required a password, you will be prompted for password for all such commands. Commented Dec 28, 2016 at 16:36

2 Answers 2

12

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.