BudiBadu Logo
Samplebadu

Shell Script by Example: Redirection

Bash 5.x

Controlling input and output streams with this code example demonstrating stdout redirection with > and >>, stderr redirection with 2>, combining streams with &>, input redirection with <, and here documents for multi-line input.

Code

#!/bin/bash

# Redirect stdout to file (overwrite)
echo "Hello" > output.txt

# Redirect stdout to file (append)
echo "World" >> output.txt

# Redirect stderr to file
ls /nonexistent 2> error.log

# Redirect both stdout and stderr to same file
ls /tmp &> all_output.log

# Redirect stderr to stdout
ls /nonexistent > output.log 2>&1

# Input redirection (read from file)
wc -l < output.txt

# Here Document (feed multi-line input)
cat <<EOF > config.txt
Host=localhost
Port=8080
EOF

Explanation

Redirection controls where commands read input from and write output to. Every process has three standard streams: stdin (file descriptor 0) for input, stdout (file descriptor 1) for normal output, and stderr (file descriptor 2) for error messages. The > operator redirects stdout to a file, overwriting existing content, while >> appends to the file. The 2> operator specifically redirects stderr, allowing you to separate error messages from normal output.

To capture both stdout and stderr in the same file, use &> filename or the older > filename 2>&1 syntax. The latter works by first redirecting stdout to the file, then redirecting stderr to wherever stdout is currently going. Order matters: 2>&1 > file doesn't work as expected because stderr is redirected before stdout is redirected to the file. This is common when logging script execution or debugging.

Input redirection < allows commands to read from files instead of the keyboard. Here Documents using <<DELIMITER provide a convenient way to pass multi-line text blocks to commands. The block continues until the delimiter (commonly EOF, END, or similar) appears alone on a line. Here Documents are frequently used for generating configuration files, feeding input to interactive programs within scripts, or creating SQL queries. You can use <<-DELIMITER to allow leading tabs in the here document, which is useful for keeping code indented inside scripts.

Code Breakdown

4
> redirects stdout to file, overwriting existing content.
7
>> appends to file instead of overwriting previous content.
10
2> redirects file descriptor 2 (stderr) to error.log.
21-24
< creates here document feeding multi-line input until EOF delimiter.