42

What is the difference between &> and >& in bash?

tldp did not mention the latter one. Is it really a redirection operator?

Or does someone know a more complete tutorial?

4 Answers 4

49

From the bash man page:

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 equiva-
   lent to

          >word 2>&1

Read the redirection section of the bash man page.

1
  • somecommand &>/dev/null is a great idiom for silencing somecommand
    – Abdull
    Jul 20, 2023 at 9:14
9

In bash, >&word and &>word (preferred syntax) redirects standard output and standard error to the same place. This is equivalent to >word 2>&1. Look it up in the bash manual.

5

man bash says

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 equiva-
lent to

       >word 2>&1
1
  • Works in sh too.
    – Mausy5043
    Apr 24, 2016 at 10:40
2

The other answers failed to mention a few caveats when quoting the 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

Namely the very important fact that:

When using the second form, word may not expand to a number or ‘-’. If it does, other 
redirection operators apply (see Duplicating File Descriptors below) for compatibility 
reasons.

This implies that if you would like for the filename of the file you redirect to, to be numeric, you are better off using the first form (i.e., &>).

Botched attempts to insist on using the first form, such as the first set of the following commands, will not produce the desired outcome:

# No go
echo hello >& '1' # Goes to stdout, instead of a file named 1
echo hello >& "1" # Ibid.
echo hello >& \1  # Ibid.
echo hello >& $(echo 1) # You guessed it... Bash is smart!

# Lift off
echo hello &> 1   # Ahh, finally, a file called 1 contains "hello"

Note: If anyone knows of (or can think of) a "simple" way that works for numeric filenames, that uses the first form (without some serious craziness like command substitution and other convolution involving subshells), I'd love to see it in the comments.

Also, do not forget that there is no such thing as &| - only the |& operator exists for stdout/stderr forwarding via a pipe - another reason to use the first form over the seconds, except when you can't.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .