How to execute a sudo script with double click
I have this script to shutdown my system after 30 seconds. I want to run this script by double clicking it (that option I changed in nautilus). This is the content of my script
#!/bin/bash
shutdown -h +30;
echo "succesfull"
read -p "Press any key to continue... " -n1 -s
to make sudo script executable without a password I followed this answer and I am able to execute this script from the terminal without using a password (sudo ~/test/test.sh
). The problem is when I double click the above script it's again asking for root privileges:
shutdown: Need to be root
successful
Press any key to continue...
What's the problem here?
You can make a conditional to relaunch the script as root if it's launched as a normal user.
To shutdown the computer:
#!/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
Simplified version:
#!/bin/bash
[[ $USER == "eka" ]] && { sudo $0; exit 0; }
[[ $USER != "root" ]] && exit 0
shutdown -h +30;
Very simplified version (not recommended):
#!/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.
To suspend the computer:
#!/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.
Simplified version:
#!/bin/bash
[[ $USER != "eka" ]] && { sudo -u eka gnome-screensaver-command -a; exit 0; }
Very simplified version:
#!/bin/bash
sudo -u eka gnome-screensaver-command -a
Note: $0
is a variable that holds the full path to the script.