[英]Can I run 'su' in the middle of a bash script?
我可以在脚本中间更改/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
您可以,但 bash 不会将后续命令作为 postgres 运行。 相反,请执行以下操作:
su postgres -c 'dropdb $user'
-c
标志以用户身份运行命令(请参阅man su
)。
您可以使用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
不是这样的。 su
将调用一个默认为 shell 的进程。 在命令行上,此 shell 将是交互式的,因此您可以输入命令。 在脚本的上下文中,shell 将立即结束(因为它无关紧要)。
和
su user -c command
command
将以user
身份执行 - 如果su
成功,通常只有无密码用户或以 root 身份运行脚本时才会出现这种情况。
使用sudo
以获得更好、更细粒度的方法。
不,你不能。 或者至少......你可以 su 但 su 将在那时简单地打开一个新的shell,完成后它将继续执行脚本的其余部分。
一种解决方法是使用su -c 'some command'
请参阅以下问题中的答案,
您可以在答案中提到的 << EOF 和 EOF 之间写。
#!/bin/bash
whoami
sudo -u someuser bash << EOF
echo "In"
whoami
EOF
echo "Out"
whoami
我今天听到的另一个有趣的想法是对脚本进行递归调用,当您以 root 身份运行并且希望以其他用户身份运行脚本时。 请参阅下面的示例:
我以“root”身份运行脚本“my_script”并希望脚本以用户“raamee”身份运行
#!/bin/bash
#Script name is: my_script
user=`whoami`
if [ "$user" == "root" ]; then
# As suggested by glenn jackman. Since I don't have anything to run once
# switching the user, I can modify the next line to:
# exec sudo -u raamee my_script and reuse the same process
sudo -u raamee my_script
fi
if [ "$user" == "raamee" ]; then
#put here the commands you want to perform
do_command_1
do_command_2
do_command_3
fi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.