19

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?

Eric Carvalho
  • 54,385
MichaelB
  • 335
  • 1
  • 2
  • 8
  • 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

1 Answers1

34

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:

Eric Carvalho
  • 54,385