Dan Eden
Dan Eden

Reputation: 1634

Escaping from sudo within a script

I have a script that calls another script as sudo. From within the second script, I want to be able to run another process without sudo permissions (the process in question is brew, which doesn't play nicely with sudo).

Here's the code in question:

scriptA.sh:

#!/bin/sh

sudo ./scriptB.sh

scriptB.sh:

#!/bin/sh

# This runs as sudo, but I need it to run as a regular user e.g. `username`
brew update

I tried su -c "brew update" -s /bin/sh username, but OS X's su doesn't allow the c flag.

Upvotes: 1

Views: 1032

Answers (2)

Barmar
Barmar

Reputation: 782498

Superuser can use the su command to become any other user. So

su otheruser -c "command to execute"

OS X su does allow the -c option. You just have to put it after the username. From the man page:

If the optional args are provided on the command line, they are passed to the login shell of the target login. Note that all command line arguments before the target login name are processed by su itself, everything after the target login name gets passed to the login shell.

In this case -c is not an option to the su command, it's an option to the login shell. And most shells take a -c option to specify a command to execute.

Upvotes: 0

chepner
chepner

Reputation: 532303

Just use sudo again:

sudo -u username brew update

Upvotes: 4

Related Questions