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 ...

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.