Sudo Commands – Pipe Password to Sudo and Other Data to Sudoed Command

bashcommand lineio-redirectionsudotee

Both of these commands work: (note the -S in sudo tells sudo to read the password from stdin).

echo 'mypassword' | sudo -S tee -a /etc/test.txt &> /dev/null
echo -e '\nsome\nmore\ntext' | sudo tee -a /etc/test.txt &> /dev/null

Now I would like to combine the two, i.e. achieve everything in just one line. But, of course, something like this doesn't work:

echo -e '\nsome\nmore\ntext' | echo 'mypassword' | sudo -S tee -a /etc/test.txt &> /dev/null

What would work? Thanks:) – Loady

PS: Minor unrelated question: is 1> identical to > ? I believe they are..

Best Answer

This will do:

{ echo 'mypassword'; echo 'some text'; } | sudo -k -S tee -a /etc/test.txt &>/dev/null

The point is sudo and tee use the same stdin, so both will read from the same source. We should put "mypassword" + "\n" just before anything we want pass to tee.

Explaining the command:

  • The curly braces groups command. We can look at {...} as one command. Whatever is in {...} writes to the pipe.
  • echo 'mypassword' will write "mypassword\n" to the pipe. This is read by sudo later.
  • echo 'some text' write "some text\n" to the pipe. This is what will reach tee at the end.
  • sudo -k -S reads password from its stdin, which is the pipe, until it reaches "\n". so "mypassword\n" will be consumed here. The -k switch is to make sure sudo prompt for a password and ignore user's cached credential if it's used recently.
  • tee reads from stdin and it gets whatever left in it, "some text\n".

PS: About I/O redirection: Yes you are right, 1>filename is identical to >filename. They both redirect stdout to filename. Also 0<filename and <filename are identical, both redirect stdin.

Related Question