4

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?

2 Answers 2

4

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.

4
  • 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 Commented Aug 3, 2017 at 11:10
  • Updated answer with bash process substitution example. Commented Aug 3, 2017 at 11:40
  • exec > >(tee $LOG) , in the bash - on the end of the script , script not return cursor Commented Aug 3, 2017 at 11:48
  • 1
    Works as expected, tested it with exec > >(tee output.txt) and cat command pastebin.com/M93MEzKe . Commented Aug 3, 2017 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)

#...

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.