I/O Redirection
Challenge Gallery
Quick Reference
| Operator | Stream | Direction | Effect |
|---|---|---|---|
> |
stdout | to file | Overwrite |
>> |
stdout | to file | Append |
< |
stdin | from file | Read input |
2> |
stderr | to file | Overwrite |
2>> |
stderr | to file | Append |
2>&1 |
stderr | to stdout | Merge streams |
&> |
both | to file | Bash shorthand for > file 2>&1 |
The three standard streams:
┌──────────┐
keyboard ──stdin──▸│ │──stdout──▸ terminal
(fd 0) │ program │ (fd 1)
│ │──stderr──▸ terminal
└──────────┘ (fd 2)
Special files:
| File | Purpose |
|---|---|
/dev/null |
Black hole – discards everything written to it |
/dev/stdin |
Alias for fd 0 |
/dev/stdout |
Alias for fd 1 |
/dev/stderr |
Alias for fd 2 |
How It Works
Output: > and »
# Overwrite
student@ubuntu:~$ ls -l > filelist.txt
# Append
student@ubuntu:~$ echo "Line 1" > myfile.txt
student@ubuntu:~$ echo "Line 2" >> myfile.txt
student@ubuntu:~$ cat myfile.txt
Line 1
Line 2
student@ubuntu:~$ ls -l > filelist.txt
# Append
student@ubuntu:~$ echo "Line 1" > myfile.txt
student@ubuntu:~$ echo "Line 2" >> myfile.txt
student@ubuntu:~$ cat myfile.txt
Line 1
Line 2
Input: <
student@ubuntu:~$ sort < names.txt
Alice
Bob
Charlie
# Combine: input from file, output to file
student@ubuntu:~$ sort < names.txt > sorted.txt
Alice
Bob
Charlie
# Combine: input from file, output to file
student@ubuntu:~$ sort < names.txt > sorted.txt
Stderr: 2> and /dev/null
# Save compiler errors to a file
student@ubuntu:~$ gcc broken.c -o broken 2> errors.txt
# Suppress permission errors from find
student@ubuntu:~$ find / -name "*.conf" 2>/dev/null
/etc/resolv.conf
/etc/sysctl.conf
# Capture everything in one file
student@ubuntu:~$ gcc program.c -o program > build.log 2>&1
student@ubuntu:~$ gcc broken.c -o broken 2> errors.txt
# Suppress permission errors from find
student@ubuntu:~$ find / -name "*.conf" 2>/dev/null
/etc/resolv.conf
/etc/sysctl.conf
# Capture everything in one file
student@ubuntu:~$ gcc program.c -o program > build.log 2>&1
Common Pitfalls
>destroys data silently. No confirmation, no undo. Use>>if you’re unsure.sort < file > fileempties the file. The shell truncates the output file before the command reads the input. Use a temp file:sort < file > tmp && mv tmp file.2>&1order matters.cmd 2>&1 > fileis NOT the same ascmd > file 2>&1. The first sends stderr to the terminal and stdout to the file. The second sends both to the file. Redirections are processed left to right.>creates files automatically.echo hi > newfile.txtcreates newfile.txt if it doesn’t exist. Notouchneeded.- Redirection is invisible to the program. The program doesn’t know its output is going to a file. It writes to stdout/stderr as usual – the shell does the wiring.