Chapter 6: I/O Redirection
Unix-like systems treat input and output as streams of data. By default, these streams are connected to your terminal, but the real power of the shell comes from your ability to reconnect these streams to files or other programs.
I. The Three Standard File Descriptors
Every process in Unix starts with three open "files" (streams) represented by integer IDs.
| ID | Name | Description | Default Source/Target |
|---|---|---|---|
| 0 | stdin | Standard Input | Your keyboard |
| 1 | stdout | Standard Output | Your terminal screen |
| 2 | stderr | Standard Error | Your terminal screen (for errors) |
II. Basic Redirection (>, >>, <)
1. Output Redirection
- Overwrite (
>):ls > files.txt(Creates or overwritesfiles.txt). - Append (
>>):echo "log entry" >> system.log(Adds to the end of the file).
2. Input Redirection
- Read from file (
<):sort < names.txt(Feeds the content ofnames.txtinto thesortcommand).
III. Handling Errors (stderr)
By default, both stdout and stderr are printed to the screen. You can redirect them separately to keep your logs clean.
# Redirect only errors to a file
ls /root 2> error.log
# Redirect stdout to one file and stderr to another
command > output.log 2> error.log
# Merge stderr into stdout (The "2>&1" idiom)
# This sends both to the same file.
command > all_output.log 2>&1
IV. The Pipeline (|)
A pipe takes the stdout of the left command and connects it to the stdin of the right command. This allows you to build complex data processing "assembly lines."
V. Advanced: Here Documents and Strings
1. Here Documents (<<)
Allows you to pass multi-line strings into a command. This is great for generating config files within a script.
cat << EOF > config.xml
<settings>
<user>$USER</user>
<mode>production</mode>
</settings>
EOF
2. Here Strings (<<<)
A shorthand for passing a single variable or string into a command's stdin.
# Instead of: echo "$VAR" | grep "search"
# Use:
grep "search" <<< "$VAR"
VI. The /dev/null Black Hole
If you want to run a command but don't care about its output or errors, you can redirect them to the "null device"—a special file that discards everything written to it.
# Silence all output and errors
command > /dev/null 2>&1
In the next chapter, we'll learn how to add logic to our scripts using Conditionals.