There are two forms of redirection the standard output and standard error into standard output. But which one is better? and why the &>
is considered the perfect?
I can't find what is the differences so that many tutorials and even bash manual state that &>
is better!
So Why shall I use &>
and not 2>&1
Mainly using bash
shell
EDIT: Thanks for commentors
Only >& works in csh or tcsh
In ksh only 2>&1 works.
dash use >file 2>&1 redirection only
Then which one to use to ensure my script is compatible with other systems whatever the used shells are!
Best Answer
Bash's man page mentions there's two ways to redirect stderr and stdout:
&> file
and>& file
. Now, notice that it says both stderr and stdout.In case of this
>file 2>&1
we are doing redirection of stdout (1) to file, but then also telling stderr(2) to be redirected to the same place as stdout ! So the purpose may be the same, but the idea slightly different. In other words "John, go to school; Suzzie go where John goes".What about preference ?
&>
is abash
thing. So if you're porting a script, that won't do it. But if you're 100% certain your script will be only working on system with bash - then there's no preferenceHere's an example with
dash
, the Debian Amquist Shell which is Ubuntu's default.As you can see, stderr is not being redirected
To address your edits in the question, you can use if statement to check $SHELL variable and change redirects accordingly
But for most cases
> file 2>&1
should workIn more technical terms, the form
[integer]>&word
is called Duplicating Output File Descriptor, and is a feature specified by POSIX Shell Command Language standard, which is supported by most POSIX-compliant and Brourne-like shells.See also What does & mean exactly in output redirection?