skip to content

Bash Redirection & Pipes

stdin, stdout, stderr redirection operators and pipeline patterns in bash.

2 min read 6 snippets 3d ago

Bash Redirection & Pipes#

Standard streams#

StreamFDDefault
stdin0keyboard
stdout1terminal
stderr2terminal

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"