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 |& operator is a pipeline control operator introduced in Bash 4.0 that simultaneously redirects both the standard output (stdout, file descriptor 1) and standard error (stderr, file descriptor 2) of the preceding command into the standard input (stdin, file descriptor 0) of the succeeding command.

Syntax

command1 |& command2

Underlying Mechanics

The |& operator functions as syntactic sugar for the standard POSIX redirection sequence 2>&1 |.

# These two pipelines are functionally identical at the system level
command1 |& command2
command1 2>&1 | command2
When the Bash parser evaluates the |& operator, it executes the following file descriptor (FD) manipulations using system calls (such as pipe() and dup2()):
  1. Pipe Creation: Initializes a unidirectional inter-process communication channel.
  2. Stdout Binding: Binds FD 1 of command1 to the write end of the pipe.
  3. Stdin Binding: Binds FD 0 of command2 to the read end of the pipe.
  4. Stderr Duplication: Duplicates FD 1 to FD 2 for command1, ensuring the error stream points to the exact same pipe buffer as the output stream.

Redirection Precedence

In Bash, redirections are processed from left to right. According to the Bash manual, the implicit 2>&1 redirection triggered by the |& operator is performed after any explicit redirections specified on the command itself. Consequently, the |& operator will override preceding explicit stderr redirections.

# 1. The explicit 2> points FD 2 to error.log.

# 2. The |& operator subsequently applies 2>&1, repointing FD 2 to the pipe.

# Result: Stderr goes to the pipe. error.log is created/truncated but remains empty.
command1 2> error.log |& command2

Compatibility Constraints

The |& operator is an extension to the POSIX shell language standard. While supported in Bash (4.0+) and Zsh (which inherited the feature from csh in its earliest versions), it behaves differently or fails in other environments:
  • POSIX Shells (sh, dash): The |& sequence is not recognized as a single token. The parser evaluates | as a standard pipe and & as a background execution operator, resulting in a syntax error.
  • KornShell (ksh): The |& operator exists but possesses entirely different semantics. In ksh, it is an asynchronous list terminator used to spawn a coprocess, connecting the command’s stdin and stdout to the parent shell. Because it acts as a command terminator (similar to & or ;), executing command1 |& command2 in ksh is perfectly valid syntax, but it does not create a pipeline. Instead, it executes command1 as a background coprocess and then executes command2 in the foreground.
For strict cross-shell compatibility, the explicit 2>&1 | syntax must be used.
Master Bash with Deep Grasping Methodology!Learn More