Search code examples
bashvariablessudo

Bash script opening new gnome-terminal with sudo password as variable


I'm making a script to keep my system up to date. In the script I open a new gnome-terminal to have the code executed there as I do want the output, but not in my main terminal window. However, I can't seem to get the sudo password to work.. Here's my script:

echo "Please provide me with your SUDO password"
#make password variable for later use. 
read password 

echo "Updating your package information.."
gnome-terminal --quiet --wait -- echo "$password" | sudo -S apt-get update
echo "Command executed."

echo -e "Upgrading packages.."
#etc..

When I just echo the password in the 'new' terminal it does work, I can see the password (or any variable) just fine. However with the above the result is always sudo: no password was provided.

I am not looking to disable my sudo password and the executed command has to be in a new window.


Solution

  • I dont use gnome, and it apparently does not have an official man page. The man page added by Debian or Ubuntu is not uptodate. It seems to suggest you need to provide the command as a single string with -e, and examples on askubuntu show it apparently working in 2010.

    More recently, -x can be used, and it then takes the rest of the line, but since you have a pipe | in your command you might need to do instead:

    ... -x bash -c "printf '%s\n' '$password' | sudo -S apt-get update"
    

    assuming ' is not in your password. (printf is preferred to echo in case of special characters in the password).

    You might prefer to pass the password in the environment instead:

    PW="$password" gnome-terminal ... -x bash -c 'printf "%s\n" "$PW" | sudo -S apt-get update'
    

    As you commented, -e and -x are now deprecated, and the command should be passed after -- as in:

    PW="$password" gnome-terminal ... -- bash -c 'printf "%s\n" "$PW" | sudo -S apt-get update'