Combining errors with output

If you want to get both the output and errors from a command, you might try it this way at first:

$ grep pattern myfile /nonexistent > matches 2> matches

However, this does not do what you might expect; you might get only the output, or only the errors, or nothing at all, depending on the system. The syntax you want is to specify a file descriptor as the redirection target, using the ampersand (&), syntax to specify 1 (the standard output stream's descriptor):

$ grep pattern myfile /nonexistent > matches 2>&1

You can read the last word of this command line as "redirect standard error to the same place standard output is already going."

Note that the order matters here; you can't put 2>&1 before > matches to accomplish the same thing. Redirections are made in order, from left to right.

There is another Bash-specific syntax, &>, to do the same thing, but the longer and more explicit method is the clearest to anyone reading your script, and works on shells besides Bash.