views:

4283

answers:

2

To redirect stdout in bash, overwriting file

cmd > file.txt

To redirect stdout in bash, appending to file

cmd >> file.txt

To redirect both stdout and stderr, overwriting

cmd &> file.txt

How do I redirect both stdout and stderr appending to file? cmd &>> file.txt does not work for me

+14  A: 
cmd >>file.txt 2>&1
Alex Martelli
works great! but is there a way to make sense of this or should I treat this like an atomic bash construct?
flybywire
TheBonsai
It says "append output (stdout, file descriptor 1) onto file.txt and send stderr (file descriptor 2) to the same place as fd1".
Dennis Williamson
That even works in zsh. Thanks.
Mark Thalman
+9  A: 

There are 2 ways, 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, in general any Bash specific code, is not the way to go.

Also remember that Bash 4 &>> is just shorter writing, it does not introduce any new functionality or similar.

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

TheBonsai