Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between "&> foo" and "> foo 2>&1"?

Tags:

bash

There seem to be two bash idioms for redirecting STDOUT and STDERR to a file:

fooscript &> foo

... and ...

fooscript > foo 2>&1

What's the difference? It seems to me that the first one is just a shortcut for the second one, but my coworker contends that the second one will produce no output even if there's an error with the initial redirect, whereas the first one will spit redirect errors to STDOUT.

EDIT: Okay... it seems like people are not understanding what I am asking, so I will try to clarify:

Can anyone give me an example where the two specific lines lines written above will yield different behavior?

like image 281
Max Cantor Avatar asked Oct 09 '08 17:10

Max Cantor


2 Answers

From the bash manual:

There are two formats for redirecting standard output and standard error:

&>word

and

>&word

Of the two forms, the first is preferred. This is semantically equivalent to

 >word 2>&1

The phrase "semantically equivalent" should settle the issue with your coworker.

like image 151
Bruno De Fraine Avatar answered Oct 06 '22 21:10

Bruno De Fraine


The situation where the two lines have different behavior is when your script is not running in bash but some simpler shell in the sh family, e.g. dash (which I believe is used as /bin/sh in some Linux distros because it is more lightweight than bash). In that case,

fooscript &> foo

is interpreted as two commands: the first one runs fooscript in the background, and the second one truncates the file foo. The command

fooscript > foo 2>&1

runs fooscript in the foreground and redirects its output and standard error to the file foo. In bash I think the lines will always do the same thing.

like image 32
Jouni K. Seppänen Avatar answered Oct 06 '22 20:10

Jouni K. Seppänen