Is there any difference beteween doing:
echo "hahaha" >> file1
and
echo "hahaha" |tee -a file1
?
Yes, I noticed that I cannot write to write protected files even aith sudo echo
, but I can if I sudo tee
. Thanks.
io-redirectionstdouttee
Is there any difference beteween doing:
echo "hahaha" >> file1
and
echo "hahaha" |tee -a file1
?
Yes, I noticed that I cannot write to write protected files even aith sudo echo
, but I can if I sudo tee
. Thanks.
Best Answer
There's no difference in the sense that the data in the file will be the same if
echo
andtee
are executed successfully and if the file is writable by the current user.The
tee
command would additionally produce output on its standard output, showing the text that would also be appended to the file. This would not happen in the first command.Another difference is that if the file can not be written to, then the first command, with the redirection, would not even run the
echo
, whereas theecho
would run in the second command, buttee
would fail in writing to the file (tee
would still produce text on the terminal though).This could be significant in the case where you run some long running process that produces output:
This would not even start
long_running_thing
iffile
was not writable.This would execute
long_running_thing
and it would run to the end, but no output would be saved intofile
if it wasn't writable (and the output would additionally be written to the terminal fromtee
).The next thing to be aware of, which you hinted at in the end of the question, is that
won't work if
file
isn't writable by the current user. This is because the redirection is processed before the command is executed (see above).To append to a root-owned file, use
Here, we run
tee
as root. Theecho
does not need to be executed by root, but the utility that actually writes to the file needs to be executed as root (or as whatever user owns the file) if it's not owned by the current user.Another possibility would be to use
or
This would use a redirection to append data to the file, but in this case, the shell that performs the redirection is running as root, so it would not fail in appending/creating the file due to restrictive permissions/ownership (it may still fail if e.g.
file
is the name of a directory).