Skip to content

Pipes & Redirection Cheat Sheet

Connect commands and control where input and output go.

Standard Streams

Stream Number Default source/destination
stdin 0 Keyboard
stdout 1 Terminal
stderr 2 Terminal

Redirection Operators

Output

Operator Meaning
> Redirect stdout to file (overwrite)
>> Redirect stdout to file (append)
2> Redirect stderr to file (overwrite)
2>> Redirect stderr to file (append)
&> Redirect both stdout and stderr to file
2>&1 Redirect stderr to where stdout currently goes
>/dev/null Discard stdout
2>/dev/null Discard stderr
&>/dev/null Discard everything
command > output.txt            # overwrite
command >> output.txt           # append
command 2> errors.txt           # errors only
command > output.txt 2>&1       # both to file
command &> output.txt           # both to file (bash shorthand)
command 2>/dev/null             # suppress errors
command > output.txt 2>/dev/null  # stdout to file, errors discarded

Input

Operator Meaning
< Redirect stdin from file
<<EOF ... EOF Here document — inline multi-line input
<<< Here string — single-line inline input
command < input.txt
sort < names.txt

cat << EOF
line 1
line 2
$variable_expands_here
EOF

command <<< "single line input"
grep "pattern" <<< "$variable"

Pipes

cmd1 | cmd2              # stdout of cmd1 → stdin of cmd2
cmd1 | cmd2 | cmd3       # pipeline of three commands
cmd1 2>&1 | cmd2         # include stderr in pipe
cmd1 |& cmd2             # bash shorthand for above

Combining Outputs

{ cmd1; cmd2; } > output.txt    # run both, capture combined stdout
{ cmd1; cmd2; } 2>&1 | cmd3    # combine and pipe

tee — Split to File AND Stdout

cmd | tee file.txt               # output to terminal AND file
cmd | tee -a file.txt            # append to file
cmd | tee file1.txt | tee file2.txt  # split to two files

Process Substitution

diff <(sort file1.txt) <(sort file2.txt)    # treat command output as file
comm <(ls dir1 | sort) <(ls dir2 | sort)
while IFS= read -r line; do ...; done < <(command)

Named Pipes (FIFO)

mkfifo mypipe
command1 > mypipe &
command2 < mypipe

File Descriptor Manipulation

exec 3>&1                  # save stdout to fd 3
exec 1> logfile.txt        # redirect all stdout to file
exec 1>&3                  # restore stdout from fd 3
exec 3>&-                  # close fd 3

exec 9> /tmp/lockfile      # open fd 9 for writing (locking)
flock -n 9 || exit 1       # acquire exclusive lock on fd 9

Quick Reference

# Run quietly — show nothing unless it fails
command > /dev/null 2>&1

# Log all output
command 2>&1 | tee -a /var/log/script.log

# Capture stderr separately from stdout
command > stdout.txt 2> stderr.txt

# Check exit code without printing output
if command > /dev/null 2>&1; then
    echo "success"
fi

# Here string: pass a variable as stdin
md5sum <<< "hello"
wc -w <<< "count these words"

Related: grep, awk, sed