Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The 2> operator is a stream redirection control operator in Bash used to redirect Standard Error (stderr)—specifically file descriptor 2—to a specified file or device. It intercepts diagnostic and error messages generated by a command before they reach the controlling terminal and writes them to the target destination, overwriting the target if it already exists.
command 2> destination

Technical Mechanics

To understand the 2> operator, it is necessary to understand POSIX file descriptors (FDs) and how the shell handles process execution. When a command is executed, the shell typically opens three standard I/O streams, each assigned an integer file descriptor:
  • 0: Standard Input (stdin)
  • 1: Standard Output (stdout)
  • 2: Standard Error (stderr)
The 2> operator is a composite of the file descriptor 2 and the output redirection operator >. When the shell parses this operator, it performs the following system-level operations:
  1. Process Forking: The shell forks a child process to execute the command.
  2. File Opening: Before executing the command, the shell opens the destination file with write-only access. It applies the O_CREAT flag (creating the file if it does not exist) and the O_TRUNC flag (truncating the file to zero length if it does exist).
  3. Descriptor Duplication: The shell uses the dup2() system call to point file descriptor 2 of the child process to the newly opened file’s descriptor.
  4. Execution: The shell calls exec() to run the command. The command remains unaware of the redirection; it simply writes its error messages to FD 2, which the kernel now routes to the specified file instead of the terminal.

Stream Isolation

The 2> operator strictly isolates the stderr stream. It does not affect Standard Output (FD 1). If a command generates both standard output and standard error, using 2> will route the errors to the specified destination, while the standard output will continue to print to the default terminal interface.

# stdout goes to the terminal; stderr goes to the file
command 2> error_stream.log
  • Appending (2>>): If the > is doubled, the shell opens the destination file with the O_APPEND flag instead of O_TRUNC. This appends the stderr stream to the end of the file rather than overwriting it.
  • Descriptor Duplication (2>&1): This syntax redirects FD 2 to whatever destination FD 1 (stdout) is currently pointing to, effectively merging the error stream into the output stream.
  • Discarding (2> /dev/null): Routing FD 2 to the null device instructs the kernel to silently discard all data written to the standard error stream.
Master Bash with Deep Grasping Methodology!Learn More