我有这个脚本,用于在 30 秒后关闭我的系统。我想通过双击它来运行这个脚本(我在 nautilus 中更改了该选项)。这是我的脚本的内容
#!/bin/bash
shutdown -h +30;
echo "succesfull"
read -p "Press any key to continue... " -n1 -s
为了使 sudo 脚本无需密码即可执行,我遵循了此操作回答我可以从终端执行此脚本而无需使用密码(sudo ~/test/test.sh
)。问题是当我双击上述脚本时,它再次要求 root 权限:
shutdown: Need to be root
successful
Press any key to continue...
这里有什么问题?
答案1
如果以普通用户身份启动脚本,则可以设置条件以 root 身份重新启动脚本。
关闭计算机:
#!/bin/bash
if [[ $USER == "eka" ]]; then # If the script is ran as "eka" then...
sudo $0 # relaunch it as "root".
exit 0 # Once it finishes, exit gracefully.
elif [[ $USER != "root" ]]; then # If the user is not "eka" nor "root" then...
exit 0 # Once it finishes, exit gracefully.
fi # End if.
shutdown -h +30;
read -p "Press any key to continue... " -n1 -s
简化版本:
#!/bin/bash
[[ $USER == "eka" ]] && { sudo $0; exit 0; }
[[ $USER != "root" ]] && exit 0
shutdown -h +30;
非常简化的版本(不推荐):
#!/bin/bash
sudo $0 # Relaunch script as root (even if it's already running as root)
shutdown -h +30; # Shutdown the computer in 30 seconds.
要暂停计算机:
#!/bin/bash
if [[ $USER == "eka" ]]; then # If the script is ran as "eka":
gnome-screensaver-command -a # Lock computer.
else # Else:
sudo -u eka gnome-screensaver-command -a # Once it finishes, exit gracefully.
fi # End if.
简化版本:
#!/bin/bash
[[ $USER != "eka" ]] && { sudo -u eka gnome-screensaver-command -a; exit 0; }
非常简化的版本:
#!/bin/bash
sudo -u eka gnome-screensaver-command -a
笔记: $0
是一个保存脚本完整路径的变量。