Bash Pipes and Redirects - |, >, >>, 2>, <, <<
Learn how to use bash pipes to chain commands and redirects to control input/output. Covers stdout, stderr, heredocs, and process substitution.
Detailed Explanation
Pipes and Redirects in Bash
Pipes and redirects are the mechanisms that make Unix shells so powerful. They allow you to connect commands together and control where input comes from and output goes.
Pipes ( | )
A pipe connects the standard output (stdout) of one command to the standard input (stdin) of the next:
# Chain commands together
ls -la | grep ".log"
cat server.log | grep "ERROR" | wc -l
ps aux | sort -k3 -rn | head -5
Each command in a pipeline runs as a separate process. Data flows from left to right, with each command processing the output of the previous one.
Output Redirects ( > and >> )
The > operator redirects stdout to a file, overwriting its contents. >> appends instead:
echo "Hello" > greeting.txt # overwrite
echo "World" >> greeting.txt # append
ls -la > filelist.txt # save directory listing
date >> log.txt # append timestamp to log
Error Redirects ( 2> and 2>> )
File descriptor 2 represents standard error (stderr). You can redirect it separately:
command 2> errors.log # redirect stderr to file
command 2>/dev/null # discard stderr
command > output.log 2>&1 # redirect both stdout and stderr
command &> combined.log # shorthand for both (bash 4+)
Input Redirects ( < )
The < operator feeds a file as stdin to a command:
sort < unsorted.txt # sort file contents
mysql < schema.sql # execute SQL file
while read line; do echo "$line"; done < data.txt
Heredocs ( << )
Heredocs provide inline multi-line input:
cat << 'EOF'
This is a multi-line
text block that preserves
formatting and indentation.
EOF
Process Substitution ( <() )
Process substitution treats command output as a file:
diff <(sort file1.txt) <(sort file2.txt)
comm -13 <(sort list1.txt) <(sort list2.txt)
Tee - Split Output
The tee command writes to both stdout and a file simultaneously:
command | tee output.log # display and save
command | tee -a output.log # display and append
Use Case
Pipes and redirects are fundamental to shell scripting and daily command-line work. System administrators use them to filter and analyze log files, developers use them in build pipelines and data processing scripts, and DevOps engineers use them in deployment automation. Mastering these operators is essential for writing efficient bash scripts.
Try It — Bash Cheat Sheet
Related Topics
Bash Text Processing - grep, sed, awk, sort, cut
Text Processing
Bash File Operations - ls, cp, mv, rm, find, chmod
File Operations
Bash For Loops - Iterating Over Lists, Ranges, and Files
Control Flow
Bash Script Basics - Shebang, Arguments, Exit Codes, set Options
Script Basics
Bash Error Handling - set -e, trap, Exit Codes, Retry Patterns
Error Handling