ReeSSult
ReeSSult

Reputation: 496

Bash output all stdout both to console and file

I am trying to output all stdout and stderr both to console and to a file. I know about ./script | tee somefile , but that doesn't work for me. I want it to do it automatically, without me piping it from the console. I've tried

#!/bin/sh
exec 2>&1 | tee somefile
echo "..."

but that didn't work. What would be the correct solution?

Upvotes: 0

Views: 698

Answers (1)

William Pursell
William Pursell

Reputation: 212178

The classical solution is to add something like this at the top of the script:

test -z "$REXECED" && { REXECED=1 exec $0 "$@" 2>&1 |  tee -a somefile; exit; }

You might also like:

test -t 1 && {  exec $0 "$@" 2>&1 |  tee -a somefile; exit; }

Upvotes: 1

Related Questions