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 a bash
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 preference
Here's an example with dash
, the Debian Amquist Shell which is Ubuntu's default.
$ grep "YOLO" * &> /dev/null
$ grep: Desktop: Is a directory
grep: Documents: Is a directory
grep: Downloads: Is a directory
grep: Music: Is a directory
grep: Pictures: Is a directory
grep: Public: Is a directory
grep: Templates: Is a directory
grep: Videos: Is a directory
grep: YOLO: Is a directory
grep: bin: Is a directory
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 work
In 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?
Most terminals (at least gnome-terminal, urxvt, and XTerm, for example) that are started within a desktop environment such as Unity will use the SHELL
environment variable to select the shell when they are launched.
SHELL
should automatically be set to your default shell listed in /etc/passwd
, but the variable can be overwritten when you log in. Make sure you have not set SHELL=/bin/bash
or something similar in a file that will affect your entire desktop session. Such files include:
~/.profile
~/.pam_environment
/etc/environment
- maybe some other files edited by Ubuntu users less often, such as
/etc/profile
Additionally if any scripts such as ~/.bashrc
or ~/.bash_profile
are called by those other startup files and there is an export SHELL=/bin/bash
line, that will also affect the entire desktop session.
I know it's acceptable/encouraged, but I still hate answering my own question. Nevertheless, this may be of some use to someone in the future. Thanks to @heemayl and @muru for helping me investigate.
Best Answer
You can type the following command in your terminal to see which shell you are using:
The result will look something similar to the below if you are using the bash (Bourne Again Shell) terminal: