如何以特定用户身份运行一行bash shell脚本

时间:2016-12-01 18:31:54

标签: bash shell sudo

我有一个手动运行的脚本(让我们说)mylogin。但是有一行需要以用户postgres运行。

这样做的好方法是什么?

如果我收到密码提示,那就没关系了。我只是需要它以某种方式工作。

这是我到目前为止所拥有的......

~/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...

我使用的是Mac OS 10.12.1。

1 个答案:

答案 0 :(得分:2)

sudo的一个参数是命令,所以你可以这样做:

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

其中-u <user>更改为目标用户