BudiBadu Logo
Samplebadu

Bash by Example: Redirection

Bash 5.0+

Controlling input and output streams using redirection operators to manage where commands read from and write to, understanding the distinction between stdout and stderr, overwriting versus appending to files, silencing command output by redirecting to /dev/null, and combining multiple redirection techniques.

Code

#!/bin/bash

file="out.log"

# 1. Standard Output (stdout) -> File
# Overwrite (>)
echo "Starting log" > "$file"
# Append (>>)
echo "Processing..." >> "$file"

# 2. Standard Error (stderr) -> File
# 2> redirects only error messages
ls non_existent_file 2> error.log
echo "Errors logged to error.log"

# 3. Redirect both stdout and stderr
# &> is the shorthand for "1>file 2>&1"
ls existing_file non_existent_file &> all.log

# 4. Discard output (The Black Hole)
# Useful for silencing noisy commands
grep "something" file.txt > /dev/null 2>&1

# 5. Input Redirection (<)
# Feed file content into command's stdin
wc -l < "$file"

rm "$file" error.log all.log

Explanation

Redirection is the mechanism for changing where commands read input from and write output to. In Unix, everything is a file, and every process starts with three open file descriptors: 0 (Standard Input), 1 (Standard Output), and 2 (Standard Error). By default, these point to your terminal.

The > operator redirects file descriptor 1 (stdout) to a file. If you want to capture error messages (which are often printed to stderr to separate them from valid data), you must use 2>. This distinction allows you to pipe valid data to the next command while logging errors to a file or discarding them.

A common idiom is command > /dev/null 2>&1. This redirects stdout to /dev/null (a special device that discards all data written to it), and then redirects stderr (2) to the same location as stdout (&1). The result is a completely silent command, which is perfect for background jobs or checking exit codes without cluttering the screen.

Code Breakdown

13
2> specifically targets the error stream. If ls succeeds, nothing goes to error.log. If it fails, the error message goes there instead of the screen.
18
&> is a convenient Bash shorthand. It captures both success output and error messages into the same file.
22
> /dev/null 2>&1. Order matters! First, stdout points to null. Then, stderr points to where stdout is pointing (null). If you swapped them, stderr would point to stdout (terminal), and then stdout would point to null.
26
< "$file" feeds the file content into wc's stdin. This is an alternative to wc -l "$file", though the latter is more common.