Reputation: 1747
So I was playing around with the language Octave, and they had this useful command called diary
that would log stdout into a file for anything in between the diary on
and diary off
diary on
a = [4 5, 2 6, 2 1]
a + 1
diary off
The above would save a file called diary in the working directory with the output of a, then a+1. It was super helpful for debugging, especially when looking at large datasets.
I was looking at other scripting languages and wondered if they have equivalents. The best I could come up with was echo hello.dat >> diary.txt
for every single line. Does a tool exist that could achieve this functionality for bash? If not, how about python? It seems like a basic thing, but idk how to do it.
Upvotes: 2
Views: 317
Reputation: 295696
If you don't need contents to keep going to the TTY, and want to redirect both stdout and stderr:
exec 3>&1 4>&2 >>diary.txt 2>&1
echo "Everything here goes to diary.txt"
echo "...without having to redirect each line separately"
exec >&3 2>&4
If you do need contents to keep going to the TTY:
exec 3>&1 4>&2 > >(tee -a diary.txt) 2>&1
echo "Everything here goes to diary.txt"
echo "...without having to redirect each line separately"
exec >&3 2>&4
Note that you can't redirect both stdout and stderr to the file without either losing their ordering (ie. having two separate copies of tee
and having to hope that they finish flushing in the same order in which you started writing to them) or lose information on which piece of output went to which descriptor.
The above can also be done with a multi-line block with a single redirection, which will do both the setup and the cleanup automatically:
{
echo "Everything here goes to diary.txt"
echo "...without having to redirect each line separately"
} >>diary.txt 2>&1
Upvotes: 3