Redirection in Bash

2015-09-10 10:04

A short note to self about redirection of stderr to stdout in bash since I keep forgetting about the &> shorthand and sometimes mix up the order when redirecting to file.

Bash supports the shorthand &> to redirect stderr and stdout to a file. The following two lines does the same thing, i.e redirects stderr and stdout to a file named logfile:

$ curl 404.example.net &> logfile
$ curl 404.example.net > logfile 2>&1

When redirecting to file it is important to notice the order. If the redirect to file is put after the redirect of stderr to stdout the result will not be sent to the file:

$ curl 404.example.net 2>&1 > logfile   # this won't work!

When sending the result to another process, i.e piping, the redirection is of course done first as expected:

$ curl 404.example.net 2>&1 | less

For complete details see Chapter 20. I/O Redirection in the Advanced Bash-Scripting Guid.