- Home
-
Linux Redirections
Linux Redirections Cheatsheet
Comprehensive guide to Linux redirections covering stdin, stdout, stderr, file descriptors, input/output redirection operators, pipes, here documents, here strings, and advanced stream manipulation techniques for bash scripting.
Master command-line efficiency with redirections and pipes. Whether you're managing a VPS hosting environment or testing server performance with our free server tools, understanding I/O redirection is essential for effective system administration.
Free account required
Understanding File Descriptors
Every Linux process has three standard streams connected to file descriptors. These are the foundation of I/O redirection. Understanding file descriptors helps when working with process management and executing basic Linux commands.
Standard Input - keyboard input by default
Standard Output - terminal screen by default
Standard Error - terminal screen for errors
Table of Contents
Input Redirection (<)
Input redirection feeds file contents to a command's standard input (STDIN) instead of keyboard input.
Basic Syntax
command < inputfile
Read input from file instead of keyboard
Example: Count lines in a file
$ wc -l < file.txt
Same as: cat file.txt | wc -l
Example: Sort file contents
$ sort < names.txt
Example: Read from file for while loop
$ while read line; do echo "$line"; done < data.txt
Output Redirection (>, >>)
Output redirection sends command output (STDOUT) to a file instead of the terminal screen.
Overwrite Output (>)
command > outputfile
Creates or overwrites the file with command output
Example: Save directory listing
$ ls -la > directory-listing.txt
Append Output (>>)
command >> outputfile
Appends output to existing file content
Example: Append to log file
$ echo "New log entry" >> application.log
$ date >> application.log
Example: Create empty file
$ > newfile.txt
# Same as: touch newfile.txt
>
overwrites the entire file! Use >>
to append instead.
Error Redirection (2>)
Error redirection sends error messages (STDERR) to a file separately from standard output.
Basic Syntax
command 2> errorfile
Redirect only error messages to file
Example: Separate errors from output
$ find / -name "*.conf" 2> errors.log
Shows results on screen, saves "Permission denied" errors to file
Example: Append errors to log
$ command 2>> error.log
Example: Suppress error messages
$ command 2> /dev/null
Discards all error messages
Combined Redirections
Combine multiple redirections to control both standard output and standard error simultaneously.
Redirect Both STDOUT and STDERR to Same File
command > output.log 2>&1
# Or modern syntax:
command &> output.log
Both output and errors go to the same file
Example: Capture all output
$ ./script.sh > full-log.txt 2>&1
$ ./script.sh &> full-log.txt # Modern syntax
Redirect STDOUT and STDERR to Different Files
command > output.log 2> error.log
Output and errors go to separate files
Example: Separate logs
$ make all > build-output.txt 2> build-errors.txt
Redirect STDERR to STDOUT (for piping)
command 2>&1 | less
Sends both output and errors through the pipe
command > file 2>&1
is correct. Writing command 2>&1 > file
won't work as expected because redirections are processed left to right.
Redirecting to /dev/null
/dev/null
is a special file that discards all data written to it. Use it to suppress unwanted output.
Discard Standard Output
command > /dev/null
Shows only errors, discards normal output
Discard Error Messages
command 2> /dev/null
Shows only normal output, discards errors
Silent Execution (Discard Everything)
command > /dev/null 2>&1
# Or modern syntax:
command &> /dev/null
Completely silent - no output or errors
Example: Check if command succeeds without output
$ if ping -c 1 google.com &> /dev/null; then
echo "Internet connection OK"
else
echo "No internet connection"
fi
Example: Silent cron jobs
$ 0 2 * * * /path/to/backup.sh > /dev/null 2>&1
Prevents cron from sending email about the job
Here Documents (<<)
Here documents allow you to pass multiple lines of input to a command. Everything between the delimiter is treated as input.
Basic Syntax
command << DELIMITER
text line 1
text line 2
DELIMITER
Example: Create multi-line file
$ cat << EOF > config.txt
server=localhost
port=8080
timeout=30
EOF
Example: Send email with heredoc
$ mail -s "Server Alert" [email protected] << EOF
Dear Admin,
Server load is high: $LOAD
Memory usage: $MEMORY%
Please check immediately.
EOF
Variables are expanded in heredocs
Example: Prevent variable expansion (quoted delimiter)
$ cat << 'EOF' > script.sh
#!/bin/bash
echo "Current user: $USER"
echo "Home dir: $HOME"
EOF
Variables are NOT expanded when delimiter is quoted
Example: Interactive SQL
$ mysql -u root -p database << SQL
CREATE TABLE users (
id INT PRIMARY KEY,
name VARCHAR(100)
);
INSERT INTO users VALUES (1, 'John');
SQL
Here Strings (<<<)
Here strings pass a single line of text as input to a command. Simpler than heredocs for single-line input.
Basic Syntax
command <<< "string"
Example: Count words in string
$ wc -w <<< "Hello World from Linux"
4
Example: Calculate MD5 hash
$ md5sum <<< "password123"
Example: Read variable into command
$ URL="https://example.com"
$ grep "example" <<< "$URL"
Example: Compare with echo piping
# Using here string (more efficient)
$ bc <<< "2 + 2"
# Using echo and pipe
$ echo "2 + 2" | bc
Pipes (|)
Pipes connect the output of one command directly to the input of another command, creating powerful command chains.
Basic Syntax
command1 | command2 | command3
Output of command1 becomes input for command2, and so on
Example: Filter and sort
$ ls -l | grep ".txt" | sort -k5 -n
List files, filter .txt files, sort by size
Example: Count unique users
$ cat access.log | cut -d' ' -f1 | sort | uniq | wc -l
Example: Search in command output
$ ps aux | grep nginx | grep -v grep
Learn more about grep patterns and options for powerful text filtering.
Example: Real-time log monitoring
$ tail -f application.log | grep ERROR
Pipe with error redirection
$ command1 2>&1 | command2
Pipes both stdout and stderr to next command
2>&1
.
File Descriptor Manipulation
Advanced redirection techniques for custom file descriptors and stream swapping.
Opening Custom File Descriptors
# Open FD 3 for reading
$ exec 3< inputfile
# Open FD 4 for writing
$ exec 4> outputfile
# Open FD 5 for appending
$ exec 5>> logfile
Reading from Custom FD
$ exec 3< data.txt
$ while read -u 3 line; do
echo "Line: $line"
done
$ exec 3<&- # Close FD 3
Writing to Custom FD
$ exec 4> output.log
$ echo "Log entry 1" >&4
$ echo "Log entry 2" >&4
$ exec 4>&- # Close FD 4
Swapping STDOUT and STDERR
$ command 3>&1 1>&2 2>&3 3>&-
Temporarily swaps stdout and stderr streams
Duplicating File Descriptors
# Save stdout to FD 6
$ exec 6>&1
# Redirect stdout to file
$ exec 1> output.log
# Commands go to output.log...
$ echo "This goes to file"
# Restore original stdout
$ exec 1>&6 6>&-
Closing File Descriptors
$ exec 3>&- # Close FD 3 (output)
$ exec 4<&- # Close FD 4 (input)
Practical Examples
These real-world examples demonstrate how redirections help with server management tasks. When running VPS benchmark tests, proper logging and error handling is crucial. Track your benchmark results using the dashboard and monitor system performance effectively.
Logging Script Output
#!/bin/bash
# Log both output and errors with timestamps
exec > >(tee -a script.log)
exec 2>&1
echo "Script started at $(date)"
# ... script commands ...
echo "Script completed at $(date)"
Backup with Progress
$ tar czf - /data | pv -s $(du -sb /data | cut -f1) > backup.tar.gz 2> backup.log
Shows progress, saves errors to log
Multi-destination Output
$ command 2>&1 | tee output.log | grep ERROR > errors.log
Saves full output and extracts errors separately
Conditional Execution Based on Output
$ if grep -q "ERROR" < application.log; then
echo "Errors found in log" | mail -s "Alert" [email protected]
fi
Batch File Processing
$ while read filename; do
echo "Processing $filename"
process "$filename" >> results.log 2>> errors.log
done < filelist.txt
Creating Detailed Reports
$ {
echo "=== System Report ==="
echo "Date: $(date)"
echo ""
echo "=== Disk Usage ==="
df -h
echo ""
echo "=== Memory Usage ==="
free -h
} > system-report.txt
Error-Only Logging
$ find / -name "*.conf" > found.txt 2> notfound.txt
Separate successful finds from permission denied errors. For advanced log analysis, check our log parsing cheatsheet.
Quick Reference Table
Operator | Description | Example |
---|---|---|
< | Input redirection | wc -l < file.txt |
> | Output redirection (overwrite) | ls > list.txt |
>> | Output redirection (append) | echo "log" >> log.txt |
2> | Error redirection | cmd 2> errors.log |
2>> | Error redirection (append) | cmd 2>> errors.log |
2>&1 | Redirect stderr to stdout | cmd > log 2>&1 |
&> | Redirect both stdout and stderr | cmd &> all.log |
&>> | Append both stdout and stderr | cmd &>> all.log |
| | Pipe (stdout to stdin) | cmd1 | cmd2 |
|& | Pipe stdout and stderr | cmd1 |& cmd2 |
<< | Here document | cat << EOF |
<<< | Here string | bc <<< "2+2" |
Need Help or Have Questions?
Explore our additional resources to learn more about VPSMetrics and how we can help optimize your server performance.
Related Linux Cheatsheets
Expand your Linux knowledge with these essential cheatsheets that complement your understanding of redirections and pipes.
Grep Command
Master text search and filtering in pipes
Linux Commands
Essential commands for daily operations
Linux Networking
Network commands and diagnostics
Docker
Container I/O and log management
Linux Filesystem
File operations and management
Log Parsing
Analyze logs with redirection techniques