我可以在脚本中间更改/ su用户吗?
if [ "$user" == "" ]; then
echo "Enter the table name";
read user
fi
gunzip *
chown postgres *
su postgres
dropdb $user
psql -c "create database $user with encoding 'unicode';" -U dbname template1
psql -d $user -f *.sql
Run Code Online (Sandbox Code Playgroud)
小智 54
你可以,但bash不会以postgres的形式运行后续命令.相反,做:
su postgres -c 'dropdb $user'
Run Code Online (Sandbox Code Playgroud)
该-c标志以用户身份运行命令(请参阅参考资料man su).
Dav*_*aun 28
您可以使用here文档su在脚本中嵌入多个命令:
if [ "$user" == "" ]; then
echo "Enter the table name";
read user
fi
gunzip *
chown postgres *
su postgres <<EOSU
dropdb $user
psql -c "create database $user with encoding 'unicode';" -U dbname template1
psql -d $user -f *.sql
EOSU
Run Code Online (Sandbox Code Playgroud)
mvd*_*vds 12
不是这样的.su将调用一个默认为shell的进程.在命令行中,此shell将是交互式的,因此您可以输入命令.在脚本的上下文中,shell将立即结束(因为它无关).
同
su user -c command
Run Code Online (Sandbox Code Playgroud)
command将被执行user- 如果su成功,通常只有无密码用户的情况或以root身份运行脚本.
使用sudo一个更好和更精细的方法.
小智 5
请参阅以下问题中的答案,
您可以在答案中提到的 << EOF 和 EOF 之间写。
#!/bin/bash
whoami
sudo -u someuser bash << EOF
echo "In"
whoami
EOF
echo "Out"
whoami
Run Code Online (Sandbox Code Playgroud)
如何使用 su 以该用户身份执行 bash 脚本的其余部分?