Ethan
Ethan

Reputation: 60089

How can I run one line of bash shell script as a specific user

I have a script I run manually (let's say) mylogin. But there's one line that needs to run as user postgres.

What is a good way to do that?

It's ok if I get a password prompt. I just need it to work somehow.

Here's what I have so far...

~/reload_test_data.sh

#!/bin/bash

# Here's the part that needs to run as user `postgres`...

sudo su postgres
export PGDATA=/Library/PostgreSQL/9.4/data && pg_ctl -m fast restart

# And here we should go back to `mylogin`...

cd ~/projects/my_project
echo 'Dropping database'
bundle exec rake db:drop

# More stuff etc...

I'm using Mac OS 10.12.1.

Upvotes: 0

Views: 193

Answers (1)

OrangesV
OrangesV

Reputation: 322

One of the arguments for sudo is the command so you can do something like:

sudo -u <user> bash -c "command_1; command_2; etc"

where -u <user> change to your target user

Upvotes: 2

Related Questions