What is the difference between &> and >& in bash?
Solution 1
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.
Solution 2
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.
Solution 3
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
Solution 4
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.
Related videos on Youtube
Comments
-
Jokester over 1 year
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?
-
Mausy5043 about 8 yearsWorks in
sh
too.