Proper way to let user enter password for a bash script using only the GUI (with the terminal hidden)
Solution 1:
The -A
sudo option allows you to specify a helper program (in the SUDO_ASKPASS variable) that will ask for the password.
Create a script to ask the password (myaskpass.sh):
#!/bin/bash
zenity --password --title=Authentication
Then insert this line at the beginning of your script:
export SUDO_ASKPASS="/path/to/myaskpass.sh"
and replace all occurences of sudo <command>
with:
sudo -A <command>
You can use whatever password asking program you want instead of zenity
. I had to encapsulate it within a script because SUDO_ASKPASS must point to a file, so it won't work with the --password
option required by zenity
.
The above works like a charm if it runs from command line or if you choose Run in terminal after double click the script file in the file manager, but if you choose Run or try to launch it from a .desktop file every sudo
will ask for the for password again.
If you don't want a terminal window at all, you can store the password in a variable and pipe it to sudo -S
. Maybe there's some security concerns, but I think it's pretty safe (read the comments on this answer).
Insert this line at the beginning of your script:
PASSWD="$(zenity --password --title=Authentication)\n"
and replace all occurences of sudo <command>
with:
echo -e $PASSWD | sudo -S <command>