Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I got a problem that:

I have a file .sh

    #!/bin/bash 

var=$(zenity --forms --title="Tắt giờ vợ yêu nhé" \
    --text="Vợ muốn tắt máy sau bao nhiêu phút nữa" \
    --separator="," \
    --add-entry="Vợ điền số vào đây")
case $? in
    0)  sudo shutdown -h $var           
    ;;
    1)
        exit 0;;
    -1)
        echo "An unexpected error has occurred."
    ;;
esac

How can sudo command autofill the password from echo command or a file. I read about sudo -S options, but i dont know how it works. Anyone can give an example about it! Thanks guys

share|improve this question

2 Answers 2

Is not very secure, just to say that before I give the answer, since somebody could just open the file and see the password but here is how:

Suppose we want to execute the command sudo shutdown -h 1 but we do not want to type in the password. We would do it like this:

echo PASSWORD | sudo -S shutdown -h1

For example, if my password were x then it would look something like this:

echo x | sudo -S shutdown -h1

Another example is, if I wanted to do an apt-get update then upgrade without entering any password. I would do this:

echo x | sudo -S apt-get update && sudo apt-get upgrade

The first sudo (The one with the -S parameter) will grab the password from the standard input, in this case, the keyboard in the terminal. It will then hold the password for the remaining terminal session. Since in this session I am executing 2 apt-get commands, one with update and the other with upgrade, there is no need to type the password again for the second apt-get since the password is active for the session in use. So the rest of the sudo commands will not need to be provided another password until the session closes (Until you close the terminal or script using the password ends).

share|improve this answer

It's better to change sudo rules instead storing clear password in a text file :

Create a new file like /etc/sudoers.d/script_rights and push

%user ALL = NOPASSWD:/sbin/shutdown

where user is the user allow to run the script.sh. Then the script will not ask the password to run the shutdown command.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.