I have some script with STDOUT and STDERR output. By default, both STDOUT and STDERR goes to console:
./script.sh
I can redirect STDOUT to file, leaving STDERR output in console:
./script.sh > log.txt
I can redirect both STDOUT + STDERR to same file with no output in console:
./script.sh > log.txt 2>&1
I can have both STDOUT and STDERR in console and logfile simultaneously:
./script.sh 2>&1 | tee -a log.txt
I don't want to see STDOUT, but I want to see STDERR, and I have to save everything in logfile. How could I have STDERR in console + logfile, while STDOUT in logfile only? Something like (pseudo-code, doesn't work):
./script.sh > log.txt 2 > /dev/tty | tee -a log.txt
You would have to append both STDERR & STDOUT to the file. Otherwise the other of the streams would write over the other.
Where:
>> log.txt
appends STDOUT tolog.txt
.2> >
sends the STDERR to to be processed by(tee -a log.txt >&2)
.tee -a log.txt
splits that to the filelog.txt
in append (-a
) mode and to>&2
.>&2
puts it back to STDERR.Considerations
Because of the appending, if you run this twice, you would have the output twice in the file – which I suppose is the goal, given it is a log file. If you would like to have only the latest run in the log file, you would have to empty it first, e.g.,
The lines would not appear in chronological order, as
>>
works a bit fastertee -a
. Because the latter has to fork another process, the output from STDERR would come to the file with a delay. If the correct order is critical, you cannot use this solution.