如何双击执行 sudo 脚本

Eka*_*Eka 6 command-line bash shutdown scripts

我有这个脚本可以在 30 秒后关闭我的系统。我想通过双击运行此脚本(我在 nautilus 中更改了该选项)。这是我脚本的内容

#!/bin/bash
shutdown -h +30;
echo "succesfull"
read -p "Press any key to continue... " -n1 -s
Run Code Online (Sandbox Code Playgroud)

不用密码化妆sudo的可执行脚本我跟着这个答案,我可以在不使用密码来执行从终端这个脚本(sudo ~/test/test.sh)。问题是当我双击上面的脚本时,它再次要求获得 root 权限:

shutdown: Need to be root
successful
Press any key to continue... 
Run Code Online (Sandbox Code Playgroud)

这里有什么问题?

0x2*_*fa0 8

如果脚本以普通用户身份启动,您可以设置以 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
Run Code Online (Sandbox Code Playgroud)

简化版:

#!/bin/bash

[[ $USER == "eka" ]] && { sudo $0; exit 0; }
[[ $USER != "root" ]] && exit 0

shutdown -h +30;
Run Code Online (Sandbox Code Playgroud)

非常简化的版本(不推荐):

#!/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.
Run Code Online (Sandbox Code Playgroud)

要挂起计算机:

#!/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.
Run Code Online (Sandbox Code Playgroud)

简化版:

#!/bin/bash

[[ $USER != "eka" ]] && { sudo -u eka gnome-screensaver-command -a; exit 0; }
Run Code Online (Sandbox Code Playgroud)

非常简化的版本:

#!/bin/bash

sudo -u eka gnome-screensaver-command -a
Run Code Online (Sandbox Code Playgroud)

注意: $0是一个保存脚本完整路径的变量。