Is there any difference beteween doing:
echo "hahaha" >> file1
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.
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
There's no difference in the sense that the data in the file will be the same if
tee are executed successfully and if the file is writable by the current user.
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 the
echo would run in the second command, but
tee 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
file was not writable.
long_running_thing | tee -a file
This would execute
long_running_thing and it would run to the end, but no output would be saved into
file if it wasn't writable (and the output would additionally be written to the terminal from
The next thing to be aware of, which you hinted at in the end of the question, is that
sudo echo hello >>file
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
echo hello | sudo tee -a file
Here, we run
tee as root. The
echo 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
sudo sh -c 'echo hello >>file'
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).
The main reason why we use Tee is to redirect the output to multiple files instead of invoking a copy command separately.
wc-l | tee -a file1.txt file2.txt file3.txt
You can elevate privilege to the tee command alone instead of the whole process, where as >> is initiated even before elevated privilege kicks in.