我想编写一个shell脚本来自动化一系列命令。问题是一些命令必须作为超级用户运行,一些命令绝不能作为超级用户运行。我到目前为止做的是这样的:
#!/bin/bash command1 sudo command2 command3 sudo command4
问题是,这意味着有人必须等到command1完成,然后提示输入密码,然后,如果command3需要足够长的时间,他们将不得不等待command3完成。这将是很好,如果这个人可以起来走开,然后回来一个小时后,完成。例如,以下脚本有此问题:
#!/bin/bash sleep 310 sudo echo "Hi,I'm root" sleep 310 sudo echo "I'm still root?"
我如何使它,使用户可以只是输入他们的密码一次,在开始,然后离开?
更新:
感谢您的回复。我在Mac OS X Lion上运行,并运行Stephen P的脚本,并得到不同的结果:(我还添加了$ HOME)
pair@abbey scratch$ ./test2.sh uid is 501 user is pair username is home directory is /Users/pair pair@abbey scratch$ sudo ./test2.sh Password: uid is 0 user is root username is root home directory is /Users/pair
文件sutest
原文链接:https://www.f2er.com/bash/391277.html#!/bin/bash echo "uid is ${UID}" echo "user is ${USER}" echo "username is ${USERNAME}"
运行它:`./sutest’给我
uid is 500 user is stephenp username is stephenp
但使用sudo:sudo ./sutest给出
uid is 0 user is root username is stephenp
因此,当以sudo运行时,您在$ USERNAME中保留原始用户名。这导致一个类似于其他人发布的解决方案:
#!/bin/bash sudo -u ${USERNAME} normal_command_1 root_command_1 root_command_2 sudo -u ${USERNAME} normal_command_2 # etc.
我最初在Linux上写了这个答案,这和OS X有一些区别
当你运行sudo时,OS X(我在Mountain Lion 10.8.3上测试这个)有一个环境变量SUDO_USER,它可以用来代替上面的USERNAME,或者脚本可以检查更多的跨平台如果SUDO_USER设置并使用它,如果是这样,或使用USERNAME如果设置。
更改OS X的原始脚本,它变成…
#!/bin/bash sudo -u ${SUDO_USER} normal_command_1 root_command_1 root_command_2 sudo -u ${SUDO_USER} normal_command_2 # etc.
跨平台的第一个刺客可以是…
#!/bin/bash # # set "THE_USER" to SUDO_USER if that's set,# else set it to USERNAME if THAT is set,# else set it to the string "unknown" # should probably then test to see if it's "unknown" # THE_USER=${SUDO_USER:-${USERNAME:-unknown}} sudo -u ${THE_USER} normal_command_1 root_command_1 root_command_2 sudo -u ${THE_USER} normal_command_2 # etc.