One little tool which's often overlooked is
tee. It is very smart and can help you so much.
tee is a typical UNIX program. It can't do much and has been created for only one purpose: writing STDIN to STDOUT and a file. That doesn't sound very exiting yet but this simple tool can do a lot for you.
tee can be used if you want to redirect the STDOUT of a program as well as printing it to the screen. A very simple example would be:
grep "myString" file.txt | tee results.txt
That searches for all occurrences of
file.txt and pipes it to
tee which prints it to the screen and writes it to the file
results.txt. In most cases the example above is not of much use but you can do more with it. Let's assume you want to write some string into two files at once. How do we do this?
echo "some text" > file1 > file2
No way! This would write
some text only to
file1 would still be empty. But yeah, we have
echo "some text" | tee file1 > file2
Now we've passed our example text to
tee which writes it to
file1 and STDOUT. The latter we've redirected to
file2. So now both files contain the same text. It's as easy as that. You see how much
tee can help you speeding up your workflow when piping together multiple operations. Of course you can extend this for writing into three, four, five and more files at once:
echo "some text" | tee file1 | tee file2 > file3
tee can also help you to avoid one problem you may have to deal with often when using
sudo. The normal output redirection operator is always executed with your user privileges, also when you write a
sudo in front of the command which generates the STDOUT text. So this would fail if you don't have permission to write to that file:
sudo echo "foo" > bar
But if you use
tee there's no problem with that:
echo "foo" | sudo tee bar
If you don't want to have
foo printed to the screen you can of course also kick
tee's output to the curb and send it to nirvana.
echo "foo" | sudo tee bar > /dev/null
tee only captures STDOUT, not STDERR. So if you want to handle STDERR you have to append it to STDOUT first:
program 2>&1 | tee file
This appends STDERR to STDOUT which then is passed to
tee that writes it to a file.
One last hint at the very end:
tee behaves like the output redirection operator
> so if the file already exists it will be overwritten. To make
tee behave like the append operator
>> use parameter
Read more about