If you’re using Codex, Claude Code, whatever your weapon of choice, you’ll see 2>&1 appended to bash commands - but what does it do?
2>&1 is a common idiom used to redirect Standard Error (stderr) to the same place as Standard Output (stdout).
To understand why this is useful, you first need to know that Linux treats everything as a file and assigns them “File Descriptors” (FD):
| File Descriptor | Name | Purpose |
|---|---|---|
| 0 | stdin | Standard Input (Keyboard) |
| 1 | stdout | Standard Output (Normal terminal text) |
| 2 | stderr | Standard Error (Error messages) |
Breaking Down the Syntax
2: Refers to the File Descriptor for Standard Error.>: The redirection operator (it sends the output of what’s on the left to what’s on the right).&: A symbol that tells Bash the following number is a File Descriptor, not a filename.1: Refers to the File Descriptor for Standard Output.
Common Use Cases
1. Saving everything to a log file
Normally, if you run command > file.txt, only the successful output is saved. If the command fails, the error message still pops up in your terminal. To catch both:
ls -l /root /tmp > output.log 2>&1
In this example, the listing for /tmp (success) and the permission error for /root (failure) both go into output.log.
2. Silencing all output
If you want a command to run “silently” without printing anything to the screen (success or failure), you send everything to /dev/null (the digital black hole):
command > /dev/null 2>&1
The Order Matters!
The redirection is processed from left to right.
- Correct:
> file 2>&1-
- Redirect stdout to the file.
-
- Redirect stderr to where stdout currently points (the file).
-
- Incorrect:
2>&1 > file-
- Redirect stderr to stdout (the terminal).
-
- Redirect stdout to the file.
- Result: Errors still appear on your screen!
-
Pro Tip: In modern Bash (version 4+), you can use a shorter “shortcut” syntax to do the exact same thing:
&> file(e.g.,ls &> output.txt)