9

Say I have a Zsh script and that I would like to let it print output to STDOUT, but also copy (dump) its output to a file in disk.

Moreover, the script starts with the following option

set -o xtrace

which forces it to be verbose and print what commands it runs. I would like to capture this output as well in a file in disk.

My understanding is that if I do

./my_script.sh > log.txt

it will just send STDOUT to log.txt, but what if I want to also be able to see the output in the terminal?

I have read about tee and the MULTIOS option in Zsh, but am not sure how to use them.

When I do:

./my_script | tee log.txt

I can see the output on the terminal, but the file log.txt doesn'tseem to be capturing everything (in fact it captures barely anything).

  • ./my_script.sh > log.txt 2>&1 – mikeserv Jun 5 '14 at 22:59
  • Looks like you're looking for the script command. Or maybe myscript >&1 > log.txt 2>&1 – Stéphane Chazelas Jun 7 '14 at 20:20
10

It could be that your script is producing output to stdout and stderr, and you are only getting one of those streams output to your log file.

./my_script.sh | tee log.txt will indeed output everything to the terminal, but will only dump stdout to the logfile.

./my_script.sh > log.txt 2>&1 will do the opposite, dumping everything to the log file, but displaying nothing on screen.

The trick is to combine the two with tee:

./myscript.sh 2>&1 | tee log.txt

This redirects stderr (2) into stdout (1), then pipes stdout into tee, which copies it to the terminal and to the log file.

The zsh multios equivalent would be:

./myscript.sh >&1 > log.txt 2>&1

That is, redirect stdout both to the original stdout and log.txt (internally via a pipe to something that works like tee), and then redirect stderr to that as well (to the pipe to the internal tee-like process).

  • Thanks -- Regarding your last line, why not ./myscript.sh >&1 2>&1 > log.txt ? (i.e. switching the order of the last two redirections). Would there be any difference between them? – Amelio Vazquez-Reina Jun 9 '14 at 12:45
  • Your variant does not output onto stdout, just to log.txt. The last line in the answer (added by @StéphaneChazelas and not myself) outputs to both. – savanto Jun 9 '14 at 16:28
0

nohup allows a job to carry on even if the console dies or is closed, useful for lengthy backups etc, but here we are using its automatic logging.

nohup myscript.sh & ; tail -f nohup.out

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.