0

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?

ReeSSult
  • 486
  • 3
  • 7
  • 21
  • https://stackoverflow.com/questions/418896/how-to-redirect-output-to-a-file-and-stdout – soft87 Sep 30 '17 at 01:00
  • @soft87: I know that. I mentioned, that I don't want to pipe it from the console, like described in that post, I want it to always do it. So even if I run `./somescript`, I will get both the file and the console output – ReeSSult Sep 30 '17 at 01:04
  • Are you wanting to do this for *all* commands you run, or just for one particular script. If the former, either run `diary` or run tee in the background reading from a pipe and redirect your shell's io streams to that pipe. If the latter, just invoke tee in the script. – William Pursell Sep 30 '17 at 01:07
  • @WilliamPursell: All commands. I may have multiple `echo` commands, and I don't want to have to pipe each of those – ReeSSult Sep 30 '17 at 01:08

1 Answers1

1

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; }
William Pursell
  • 204,365
  • 48
  • 270
  • 300