pipe password to `sudo` and other data to `sudo`ed command

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.