Redirect stderr to stdout

Originally written: May 21st, 2022

Redirecting stderr to stdout is a common activity while shell scripting, yet I can never remember how to do it.
Here is a basic summary of file piping in bash.

First, basics: 1> is outputting to stdout, while 2> is outputting to stderr. > is a shortcut for 1>, and most people remember how to redirect to a file: command > file -- which means, equivalently, command 1> file. Redirecting stderr to a file is command 2> stderr.

To redirect stderr to stdout, you do 2>&1 (conversely, to redirect stdout to stderr, you would do 1>&2). To redirect both stderr and stdout to a file, then you need to do:

                command >file 2>&1
The order is important; if you do command 2>&1 >file, then stderr will be redirected to stdout before stdout is redirected to the file.

However, this use case is common enough that 2>&1 can be abbreviated as &>. You only need to really remember how to do this:

                command &> file