Ubuntu – Redirect terminal output to file

bashcommand line

I am looking for a bash command where I can redirect:

  1. stdout of a command to a file
  2. stderr to both that file and the console.

I have found ways where the stderr will append to the end of the file after the stdout, but I want it so that the output file orders all out the output chronologically like it would if I were to just use command &> file.

I have tried:

command 2>&1 1>logfile | tee -a logfile
command 2> >(tee -a logfile) 1>>logfile

I would basically like the output file to be same as if I simply did command &> logfile, whilst at the same time keep printing stderr messages to the console.

Best Answer

Let's create a test function that sends some output to both stdout and stderr:

$ cmd() { echo 1 on stdout; echo 2 on stderr >&2; echo 3 on stdout; echo 4 on stderr >&2; }

Running it we see:

$ cmd
1 on stdout
2 on stderr
3 on stdout
4 on stderr

Now, we want to send the stdout to a file, and the stderr to both the file and the screen. For this we use a simple redirection for stdout, and for stderr we redirect into a process substitution that appends to the file and sends the output back to stderr:

$ cmd > cmd.out 2> >( tee -a cmd.out >&2 )
2 on stderr
4 on stderr

$ cat cmd.out
1 on stdout
3 on stdout
2 on stderr
4 on stderr

I do not know of a way to keep the chronological order of the intermixed stdout and stderr messages.