Bash Redirection & Pipes#
Standard streams#
| Stream | FD | Default |
|---|---|---|
| stdin | 0 | keyboard |
| stdout | 1 | terminal |
| stderr | 2 | terminal |
Redirection operators#
# Redirect stdout to file (overwrite)
command > file.txt
# Redirect stdout (append)
command >> file.txt
# Redirect stderr
command 2> error.log
# Redirect both stdout and stderr to same file
command &> all.log
command > all.log 2>&1 # older form, POSIX portable
# Discard output
command > /dev/null 2>&1
# Redirect stdin from file
command < input.txt
# Here-doc (multiline stdin)
cat <<EOF
line one
line two
EOF
# Here-string (single line stdin)
base64 <<< "hello world"
Pipes#
# Basic pipe
ps aux | grep nginx
# Pipe stderr through pipe (bash 4+)
command 2>&1 | grep ERROR
# Pipe with tee (write to file AND stdout)
make 2>&1 | tee build.log
# Process substitution (pipe without subshell for IDs)
diff <(sort file1.txt) <(sort file2.txt)
# Named pipe (FIFO)
mkfifo /tmp/mypipe
tail -f /var/log/syslog > /tmp/mypipe &
grep "ERROR" < /tmp/mypipe
Useful patterns#
Capture stderr into a variable (discard stdout):
err=$(command 2>&1 >/dev/null)
Run command, capture all output, and check exit code:
if ! output=$(some-command 2>&1); then
echo "Failed: $output" >&2
exit 1
fi
Swap stdout and stderr:
command 3>&1 1>&2 2>&3 3>&-
Tail a live log with colour preserved through the pipe:
tail -f /var/log/auth.log | grep --color=always "Failed"