Streams & Redirection
Every program in Linux has three standard data streams, each identified by a file descriptor number:
- stdin (0): Standard input โ data going into a command (usually from the keyboard).
- stdout (1): Standard output โ normal output from a command.
- stderr (2): Standard error โ error messages from a command.
Output Redirection
Redirection lets you send the output of a command to a file instead of the screen.
# > overwrites the file (creates it if it doesn't exist)
echo "Hello" > output.txt
# >> appends to the file
echo "World" >> output.txt
# Redirect stderr to a file
ls /nonexistent 2> errors.txt
# Redirect both stdout and stderr to the same file
command &> all_output.txt
# or
command > output.txt 2>&1Input Redirection
# Feed a file into a command
sort < unsorted.txt
# Combine input and output redirection
sort < unsorted.txt > sorted.txt> as an arrow pointing where the output should go. > sends stdout to a file; 2> sends stderr to a file.
Pipes
Pipes (|) connect the stdout of one command to the stdin of the next. They're one of the most powerful features in Bash.
# Count files in a directory
ls | wc -l
# Find a process
ps aux | grep nginx
# Chain multiple pipes
cat access.log | grep "404" | sort | uniq -c | sort -rn | headThe tee Command
tee reads from stdin and writes to both stdout and a file simultaneously. It's like a T-junction in plumbing.
# Display output AND save it to a file
ls -la | tee listing.txt
# Append instead of overwrite
echo "new line" | tee -a logfile.txt/dev/null โ The Black Hole
/dev/null is a special device that discards all data written to it. It's useful when you want to suppress output.
# Discard stdout
command > /dev/null
# Discard stderr
command 2> /dev/null
# Discard everything
command &> /dev/nullHere Documents
A here document lets you pass multi-line input to a command inline.
cat <<EOF
This is line one.
This is line two.
Variable expansion works: $USER
EOF
# Here string (single line)
grep "hello" <<< "hello world"EOF) must appear on its own line with no leading spaces (unless you use <<- which strips leading tabs).
Try It Yourself
Summary
You've learned the three standard streams, output/input redirection with >, >>, and <, how to pipe commands together with |, the tee command, /dev/null, and here documents. These concepts are fundamental to everything in Bash scripting.