2

I need to write the standard err and standard output to $LOG, while also having them printed on console, from within a script.

The script has many commands, so redirecting each one of them is not a good solution.

I've tried this, but it didn't work as expected:

#!/bin/bash

LOG=/var/tmp/log

#...

exec > $LOG  2>&1

My target is to write to $LOG on any standard output and standard error, but on the same time also to the standard output (on console). Is it possible?

1

Use tee. For example:

command 2>&1 | tee file.txt

Which runs command redirecting SDTERR to SDTOUT. tee copies STDIN to both STDOUT and to file file.txt.

In bash you can use process substitution in following way to copy output to $LOG:

exec &> >(tee $LOG)

However this bashism won't work on other shells.

  • I dont want to add to each command tee -a I have around 200 commands in my script , my target is to change the "exec > $LOG 2>&1" in order to support also printing on the console – yael Aug 3 '17 at 11:10
  • Updated answer with bash process substitution example. – sebasth Aug 3 '17 at 11:40
  • exec > >(tee $LOG) , in the bash - on the end of the script , script not return cursor – yael Aug 3 '17 at 11:48
  • 1
    Works as expected, tested it with exec > >(tee output.txt) and cat command pastebin.com/M93MEzKe . – sebasth Aug 3 '17 at 11:59
0

I'm not sure if this is the most clean solution but it worked for me:

#!/bin/bash

LOG=/var/tmp/log

(
# lots of commands
# ...

) 2>&1 | tee $LOG

@sebasth gave a better solution, though:

#!/bin/bash

LOG=/var/tmp/log

exec &> >(tee $LOG)

#...

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.