RED HAT ENTERPRISE LINUX
Input-Output
Redirection
Use input-output redirection (>, >>, |, 2>, etc.)
CIS126RH | RHEL System Administration 1
Mesa Community College
Every Linux command reads input from somewhere and writes output somewhere. By default that is the keyboard and the screen — but the shell lets you redirect input and output to files, other commands, and special destinations. Mastering redirection transforms the command line from a simple tool into a powerful data-processing environment. This skill is tested on the RHCSA exam.
Learning Objectives
- Explain standard streams — Describe stdin, stdout, and stderr and their file descriptor numbers
-
Redirect output to a file —
Use
>to overwrite and>>to append -
Redirect and discard error output —
Use
2>,2>>, and&>to handle stderr separately from stdout -
Redirect input and use pipes —
Use
<to feed a file into a command, and|to chain commands together
Standard Streams
Every process on Linux has three standard data streams open by default.
| Stream | Name | File descriptor | Default source or destination |
|---|---|---|---|
| stdin | Standard input | 0 |
Keyboard |
| stdout | Standard output | 1 |
Terminal screen — normal output |
| stderr | Standard error | 2 |
Terminal screen — error messages |
Redirection operators tell the shell to connect these streams to a file or another command instead of the keyboard or screen.
Keeping normal output (stdout) and error messages (stderr) separate lets you save useful output to a file while still seeing errors on screen — or log errors separately from results.
Output Redirection: > and >>
These operators redirect stdout — the normal output of a command — to a file.
| Operator | Effect | If the file already exists |
|---|---|---|
> |
Write stdout to a file | Overwrites the existing content |
>> |
Append stdout to a file | Adds to the end — existing content is preserved |
# Save the output of date to a file — creates or overwrites
$ date > /tmp/timestamp.txt
$ cat /tmp/timestamp.txt
Mon May 25 10:00:00 MST 2026
# Overwrite with a second date — the first line is gone
$ date > /tmp/timestamp.txt
# Append — both dates are now in the file
$ date >> /tmp/timestamp.txt
$ cat /tmp/timestamp.txt
Mon May 25 10:01:00 MST 2026
Mon May 25 10:02:00 MST 2026
# Save a list of installed packages for later review
$ rpm -qa > /tmp/packages.txt
The > operator destroys the existing file contents without asking.
Use >> when you need to preserve what is already there.
Creating and Truncating Files
Redirection operators can create files and empty existing ones without running a command.
Create an Empty File
# Redirect no output to a new file — creates it empty
$ > newfile.txt
# The traditional way to create empty files
$ touch newfile.txt
Empty an Existing File Without Deleting It
# Truncate a log file to zero bytes — keeps the file, clears the content
$ > /var/log/myapp.log
# Useful before a test run — start with a clean log
$ > /tmp/test.log
$ ./my-script.sh >> /tmp/test.log
Truncating a log with > logfile is safer than deleting and recreating it.
Running processes that have the file open continue writing to the same inode — a new file
would not be picked up until the process is restarted.
Redirecting stderr: 2>
The 2 in 2> refers to file descriptor 2 — stderr.
This lets you capture or discard error messages independently of normal output.
# A command that produces both stdout and stderr
$ find /etc -name '*.conf'
/etc/ssh/sshd_config
find: '/etc/ssl/private': Permission denied
/etc/resolv.conf
# Redirect only stderr to a file — errors are saved, results still print
$ find /etc -name '*.conf' 2> /tmp/errors.txt
# Discard error messages entirely — send them to /dev/null
$ find /etc -name '*.conf' 2> /dev/null
# Append errors to a log file
$ find /etc -name '*.conf' 2>> /tmp/errors.txt
/dev/null is a special file that discards everything written to it.
Redirecting to /dev/null is the standard way to silence unwanted output.
Redirecting Both Streams
Sometimes you need to capture or discard both stdout and stderr together.
| Operator | Meaning |
|---|---|
&> |
Redirect both stdout and stderr to a file — overwrites |
&>> |
Redirect both stdout and stderr to a file — appends |
2>&1 |
Redirect stderr to wherever stdout is currently going |
# Save all output and all errors to one log file
$ ./backup-script.sh &> /var/log/backup.log
# Older POSIX-compatible syntax — same result as >
$ ./backup-script.sh > /var/log/backup.log 2>&1
# Discard ALL output — run silently
$ ./noisy-script.sh &> /dev/null
When using the older syntax, always write > file 2>&1 — not
2>&1 > file. The shell processes redirections left to right.
Putting 2>&1 first sends stderr to the screen before stdout is
redirected to the file.
Input Redirection: <
The < operator feeds the contents of a file into a command as stdin,
replacing keyboard input.
# Send the contents of a file to a command's stdin
$ sort < names.txt
Alice
Bob
Carol
# The above is equivalent to — sort reads the file either way
$ sort names.txt
# Mail a report file to a user
$ mail -s "Weekly report" admin@example.com < report.txt
# Count the words in a file via stdin
$ wc -w < document.txt
342
Some commands only read from stdin and cannot take a filename as an argument.
For those commands, < is the only way to feed them file contents.
Here Documents and Here Strings
These are special forms of input redirection that embed input directly in the command line or script — without needing a separate file.
Here Document — <<WORD
# Feed multiple lines to a command inline
$ cat <<EOF
Line one
Line two
Line three
EOF
# Write a config file using a here document
$ sudo tee /etc/motd <<EOF
Authorized users only.
All activity is logged.
EOF
Here String — <<<
# Feed a single string to stdin
$ grep root <<< "root:x:0:0:root:/root:/bin/bash"
root:x:0:0:root:/root:/bin/bash
The Pipe Operator |
A pipe connects the stdout of one command directly to the stdin of the next. The two commands run simultaneously — no temporary file is created.
# Count how many lines contain 'error'
$ grep -i error /var/log/messages | wc -l
42
# List running processes and find a specific one
$ ps aux | grep httpd
# Show the ten largest files in /var/log
$ du -sh /var/log/* | sort -rh | head
# Page through a long man page
$ man sshd_config | less
A pipe passes stdout to the next command. stderr is not included — it still goes to the
screen unless you explicitly redirect it before the pipe:
command 2>&1 | nextcommand
Building Pipelines
Multiple pipes can be chained together. Each command processes the output of the one before it.
# Top 5 IP addresses in failed SSH login attempts
$ grep 'Failed password' /var/log/secure |
grep -oE '[0-9]{1,3}(\.[0-9]{1,3}){3}' |
sort |
uniq -c |
sort -rn |
head -5
# Count unique shells in use across all accounts
$ cut -d: -f7 /etc/passwd | sort | uniq -c
# Show active (non-comment, non-blank) sshd settings
$ grep -vE '^(#|$)' /etc/ssh/sshd_config | sort
Add one command at a time when building a pipeline. Run the partial pipeline, inspect the output, then add the next stage. This makes debugging much easier than writing the whole pipeline at once.
tee: Redirect and Display
tee reads from stdin and writes to both a file and stdout at the same time.
It is used in the middle of a pipeline when you need to save intermediate output
without breaking the pipeline.
# Display output on screen AND save it to a file
$ ls -l /etc | tee /tmp/etc-listing.txt | wc -l
192
# Append mode — do not overwrite the file
$ df -h | tee -a /tmp/disk-report.txt
# Write to a root-owned file from a pipeline using sudo tee
$ echo 'PasswordAuthentication no' |
sudo tee -a /etc/ssh/sshd_config
You cannot use sudo > file to write to a root-owned file because the shell
handles redirection before sudo runs. The workaround is to pipe to
sudo tee filename, which runs tee as root.
Common Pipeline Commands
These commands appear frequently in pipelines with redirection operators.
| Command | What it does | Common use |
|---|---|---|
sort | Sort lines alphabetically or numerically | Order output before counting unique values |
uniq | Remove or count duplicate adjacent lines | Use after sort — uniq -c counts occurrences |
cut | Extract fields or characters from each line | cut -d: -f1 extracts field 1 from colon-delimited lines |
wc | Count lines, words, or characters | wc -l counts lines of output |
head | Show the first N lines | Preview large output or show top results |
tail | Show the last N lines | tail -f follows a growing log file |
tr | Translate or delete characters | Convert case, remove characters |
less | Page through output interactively | Browse long output without scrolling past it |
Redirection Quick Reference
| Operator | Full name | Effect |
|---|---|---|
> file | Stdout redirect — overwrite | Write stdout to file, replacing contents |
>> file | Stdout redirect — append | Add stdout to end of file |
2> file | Stderr redirect — overwrite | Write stderr to file, replacing contents |
2>> file | Stderr redirect — append | Add stderr to end of file |
&> file | Combined redirect — overwrite | Write both stdout and stderr to file |
&>> file | Combined redirect — append | Append both stdout and stderr to file |
2>&1 | Stderr to stdout | Merge stderr into stdout stream |
< file | Stdin redirect | Feed file contents as stdin |
<<WORD | Here document | Feed inline multi-line text as stdin |
<<< string | Here string | Feed a single string as stdin |
| | Pipe | Connect stdout of one command to stdin of the next |
Redirection in Real Admin Tasks
Save a Report and Log Errors Separately
$ find /home -name '*.log' \
> /tmp/log-files.txt \
2> /tmp/find-errors.txt
Capture Script Output for Audit
$ bash setup.sh &> /var/log/setup-$(date +%F).log
Watch a Log File in Real Time
$ tail -f /var/log/messages | grep -i error
Write to a Root-Owned File from a Pipeline
$ echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
Feed a SQL Script into a Database Client
$ mysql -u root mydb < schema.sql
Common Mistakes
| Mistake | What goes wrong | Correct form |
|---|---|---|
Using > when >> was intended |
Existing file content is silently destroyed | Use >> to preserve content |
Writing 2>&1 > file |
stderr still goes to screen; only stdout goes to file | Write > file 2>&1 — stdout first |
sudo > /root/file |
Permission denied — shell redirects before sudo runs | command | sudo tee /root/file |
| Piping stderr into the next command without merging | Error messages bypass the pipeline and appear on screen | Add 2>&1 before the pipe: cmd 2>&1 | next |
| Redirecting output to the same file used as input | The shell truncates the file before the command reads it | Use a temporary file, then move it into place |
Knowledge Check
Answer these before moving to the next slide.
- What are the three standard streams, and what is the file descriptor number for each?
- What is the difference between
>and>>? - Write a command that runs
find /etc -name '*.conf'and sends error messages to/dev/nullwhile displaying normal output on screen. - What does
2>&1mean, and why does order matter when combining it with> file? - What does the pipe operator
|connect, and does it carry stderr? - Why does
sudo echo 'text' > /etc/filefail, and how do you fix it?
Knowledge Check — Answers
-
stdin (file descriptor 0) — standard input, default source is the keyboard.
stdout (file descriptor 1) — standard output, default destination is the screen.
stderr (file descriptor 2) — standard error, default destination is the screen. >overwrites the file — any existing content is destroyed.>>appends to the file — existing content is preserved.find /etc -name '*.conf' 2> /dev/null2>&1means "send stderr to wherever stdout is currently pointing." Order matters because the shell processes redirections left to right.> file 2>&1first points stdout at the file, then points stderr at stdout — so both go to the file.2>&1 > filefirst points stderr at the screen (where stdout is before the redirect), then redirects stdout to the file — leaving stderr on screen.- The pipe connects the stdout of the left command to the
stdin of the right command. It does not carry stderr —
stderr still goes to the screen unless explicitly merged with
2>&1before the pipe. - The shell handles the
>redirection before running sudo, so the file is opened by the unprivileged shell process and fails with permission denied. Fix:echo 'text' | sudo tee /etc/file— tee runs as root and opens the file.
Key Takeaways
- Every process has three standard streams. stdin (0), stdout (1), and stderr (2) are open by default. Redirection operators reconnect these streams to files or other commands.
-
>overwrites;>>appends. Use>>when you need to preserve existing file content. Use2>to capture errors separately and2> /dev/nullto discard them. -
The pipe
|is the most powerful operator. It connects stdout of one command to stdin of the next, enabling complex data processing from simple tools. Pipes carry stdout only — merge stderr with2>&1to include it. -
Write
> file 2>&1— not the other way around. Redirect stdout first, then point stderr at stdout. Usesudo teewhen writing to root-owned files from a pipeline.
Graded Lab
- Redirect the output of
dateto/tmp/mydate.txt, then append a seconddateoutput — confirm both lines are in the file - Run
find /etc -name '*.conf'and redirect errors to/dev/null— only file paths should appear on screen - Run
find /etc -name '*.conf'and send stdout to/tmp/confs.txtand stderr to/tmp/conf-errors.txtsimultaneously - Use a pipeline with
grep,sort, anduniq -cto count how many accounts in/etc/passwduse each login shell - Use
tail -f /var/log/messages | grep -i errorin one terminal while generating activity in another — observe filtered live output - Use
echopiped tosudo tee -ato append a comment line to/etc/hosts
"Use input-output redirection (>, >>, |, 2>, etc.)" — Redirection appears in almost every other exam task. Fluency here multiplies your effectiveness across the entire exam.