我能跑';苏';在BASH脚本的中间? 我可以在脚本中间改变/SU用户吗?< /P> 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运行。相反,要:我能跑';苏';在BASH脚本的中间? 我可以在脚本中间改变/SU用户吗?< /P> 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,shell,Bash,Shell,可以,但是bash不会将后续命令作为postgres运行。相反,要: su postgres -c 'dropdb $user' -c标志以用户身份运行命令(请参见mansu)。不,您不能。或者至少。。。您可以使用su,但su只需在此时打开一个新shell,完成后,它将继续执行脚本的其余部分 一种解决方法是使用su-c“some命令”而不是像这样su将调用一个进程,该进程默认为shell。在命令行上,此shell将是交互式的,因此您可以输入命令。在脚本的上下文中,shell将立即结束(因为它与
su postgres -c 'dropdb $user'
-c
标志以用户身份运行命令(请参见mansu
)。不,您不能。或者至少。。。您可以使用su,但su只需在此时打开一个新shell,完成后,它将继续执行脚本的其余部分
一种解决方法是使用
su-c“some命令”
而不是像这样su
将调用一个进程,该进程默认为shell。在命令行上,此shell将是交互式的,因此您可以输入命令。在脚本的上下文中,shell将立即结束(因为它与脚本无关)
与
命令
将作为用户
执行-如果su
成功,这通常仅适用于无密码用户或以root用户身份运行脚本的情况
使用
sudo
可以获得更好、更细粒度的方法。我今天听到的另一个有趣的想法是,当您以root用户身份运行并且希望以其他用户身份运行脚本时,对脚本执行递归调用。请参见下面的示例:
我正在以“root”身份运行脚本“my_script”,并希望该脚本以用户“raamee”身份运行
您可以使用在脚本中嵌入多个
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
如果[“$user”=”;然后
echo“输入表名”;
读用户
fi
枪口*
周博士后*
su博士后参考以下问题的答案
你可以在两行之间写,如果你想在那里使用双引号:su postgres-c“dropdb$user”
如果结束引号出现在另一行,你可以放多行。在这种情况下,请注意引用。如果在“raamee”起作用后您无事可做,那么您可以:exec sudo-u raamee my_script
——它将替换当前进程,而不是将其挂起。这很聪明,但here文档更简单(请参见我的答案)。要记住的一点是sudo`d用户(如果不是root用户)需要具有运行脚本本身的权限。可能的重复小心,我认为如果将某些字符(如backtick)放入here文档中,则需要对其进行转义。还要小心,在将其传递给su
之前,替换了herdoc中的所有变量。当您在内部创建和使用变量时,这可能是一个问题。为了避免这种情况,关闭参数替换,将第一个EOSU
用单引号括起来,如:su postgres向sudo添加-i以获取某个用户的环境。
#!/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
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
#!/bin/bash
whoami
sudo -u someuser bash << EOF
echo "In"
whoami
EOF
echo "Out"
whoami