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:
The point is
sudo
andtee
use the same stdin, so both will read from the same source. We should put "mypassword" + "\n" just before anything we want pass totee
.Explaining the command:
{...}
as one command. Whatever is in{...}
writes to the pipe.echo 'mypassword'
will write "mypassword\n" to the pipe. This is read bysudo
later.echo 'some text'
write "some text\n" to the pipe. This is what will reachtee
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 suresudo
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. Also0<filename
and<filename
are identical, both redirect stdin.