January 23, 2013

A bashism a week: output redirection

Redirecting stdout and stderr to the same file or file descriptor with &> is common and nice, except that it is not required to be supported by POSIX:2001. Moreover, trying to use it with shells not supporting it will do exactly the opposite:

  1. The command's output (to stdout and stderr) won't be redirected anywhere.
  2. The command will be executed in the background.
  3. The file will be truncated, if redirecting to a file and not using >>.

Are the characters saved worth those effects? I don't think so. Just use this instead: "> file 2>&1". Make sure you get the first redirection right, "&> file 2>&1" isn't going to do the trick.


  1. The space isn’t even needed, so “>file 2>&1” is fine, or “>>file 2>&1”.

    The order of these two is important though. If you want to redirect both stdout and stderr, the “2>&1” must come after the stdout redirection, not before. (The mksh manpage has more on this.)

  2. mksh no longer parses the GNU bash “&>” extension when in POSIX or /bin/sh mode because it changes the meaning of previously correct scripts (thanks to the guys in #!/bin/mksh on Freenode IRC for pointing this out):

    1) "$__progname" -c 'echo foo>/dev/null&>/dev/fd/2 echo bar1'
    2) "$__progname" -o posix -c 'echo foo>/dev/null&>/dev/fd/2 echo bar2'
    1) foo echo bar1
    2) bar2