I want to run a command that requires the sudo password say:

sudo apt-get update

Isn't this supposed to work (I have stored the password in a normal text file passwd.txt):

sudo apt-get update <~/passwd.txt

This is my logic for for why it SHOULD work: when the password is required, the user is asked to input the password from the keyboard. But redirecting the stdin to read from the passwd.txt file should work.

Shouldn't it?

  • Read sudo with password in one command line?.
    – edwin
    Jul 21 '13 at 16:44
  • You would noramlly use expect tcl script to automate such things.
    – Adobe
    Jul 21 '13 at 20:00
  • If you need to ask this, you're probably doing something wrong. Could you share what you're trying to accomplish in the first place? One should never have to use hacks like this. It's an indication that there should be a better solution.
    – gertvdijk
    Jul 22 '13 at 11:18
  • @gertvdijk I am not an expert of ubuntu but I m learning. I gave this to myself as an exercise: "Execute a command in a Bash Script that requires sudo privilege using only the knowledge that I currently possess. Without using Google." I came up with the above answer and I thought tht it should work. I found better, safer solutions on AskUbuntu later.
    – MichaelB
    Jul 22 '13 at 15:22

sudo doesn't read password from stdin by default. From sudo manpage:

-S  The -S (stdin) option causes sudo to read the password from the standard input instead of the terminal device.
    The password must be followed by a newline character.

So you should run:

sudo -S apt-get update <~/passwd.txt

Keep in mind that storing passwords in files is not a good practice. You should read:

  • Understood! Short n sweet answer!
    – MichaelB
    Jul 21 '13 at 17:29
  • 1
    to make it self-documenting I would just use sudo --stdin apt-get update May 4 '20 at 15:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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