How to redirect and append both standard output and standard error to a file with Bash

ID : 578

viewed : 138

Tags : bashappendstdoutio-redirectionstderrbash

Top 5 Answer for How to redirect and append both standard output and standard error to a file with Bash

vote vote

98

cmd >>file.txt 2>&1 

Bash executes the redirects from left to right as follows:

  1. >>file.txt: Open file.txt in append mode and redirect stdout there.
  2. 2>&1: Redirect stderr to "where stdout is currently going". In this case, that is a file opened in append mode. In other words, the &1 reuses the file descriptor which stdout currently uses.
vote vote

88

There are two ways to do this, depending on your Bash version.

The classic and portable (Bash pre-4) way is:

cmd >> outfile 2>&1 

A nonportable way, starting with Bash 4 is

cmd &>> outfile 

(analog to &> outfile)

For good coding style, you should

  • decide if portability is a concern (then use classic way)
  • decide if portability even to Bash pre-4 is a concern (then use classic way)
  • no matter which syntax you use, not change it within the same script (confusion!)

If your script already starts with #!/bin/sh (no matter if intended or not), then the Bash 4 solution, and in general any Bash-specific code, is not the way to go.

Also remember that Bash 4 &>> is just shorter syntax — it does not introduce any new functionality or anything like that.

The syntax is (beside other redirection syntax) described here: http://bash-hackers.org/wiki/doku.php/syntax/redirection#appending_redirected_output_and_error_output

vote vote

70

In Bash you can also explicitly specify your redirects to different files:

cmd >log.out 2>log_error.out 

Appending would be:

cmd >>log.out 2>>log_error.out 
vote vote

70

This should work fine:

your_command 2>&1 | tee -a file.txt 

It will store all logs in file.txt as well as dump them in the terminal.

vote vote

53

In Bash 4 (as well as Z shell (zsh) 4.3.11):

cmd &>> outfile 

just out of box.

Top 3 video Explaining How to redirect and append both standard output and standard error to a file with Bash

Related QUESTION?