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

  1. Explain standard streams — Describe stdin, stdout, and stderr and their file descriptor numbers
  2. Redirect output to a file — Use > to overwrite and >> to append
  3. Redirect and discard error output — Use 2>, 2>>, and &> to handle stderr separately from stdout
  4. 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.

Why two output streams?

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
Overwrite Warning

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
Tip

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

/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
Order Matters with 2>&1

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
When input redirection is essential

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
Pipes only carry stdout

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
Build incrementally

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
sudo tee pattern

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
sortSort lines alphabetically or numericallyOrder output before counting unique values
uniqRemove or count duplicate adjacent linesUse after sortuniq -c counts occurrences
cutExtract fields or characters from each linecut -d: -f1 extracts field 1 from colon-delimited lines
wcCount lines, words, or characterswc -l counts lines of output
headShow the first N linesPreview large output or show top results
tailShow the last N linestail -f follows a growing log file
trTranslate or delete charactersConvert case, remove characters
lessPage through output interactivelyBrowse long output without scrolling past it

Redirection Quick Reference

Operator Full name Effect
> fileStdout redirect — overwriteWrite stdout to file, replacing contents
>> fileStdout redirect — appendAdd stdout to end of file
2> fileStderr redirect — overwriteWrite stderr to file, replacing contents
2>> fileStderr redirect — appendAdd stderr to end of file
&> fileCombined redirect — overwriteWrite both stdout and stderr to file
&>> fileCombined redirect — appendAppend both stdout and stderr to file
2>&1Stderr to stdoutMerge stderr into stdout stream
< fileStdin redirectFeed file contents as stdin
<<WORDHere documentFeed inline multi-line text as stdin
<<< stringHere stringFeed a single string as stdin
|PipeConnect 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.

  1. What are the three standard streams, and what is the file descriptor number for each?
  2. What is the difference between > and >>?
  3. Write a command that runs find /etc -name '*.conf' and sends error messages to /dev/null while displaying normal output on screen.
  4. What does 2>&1 mean, and why does order matter when combining it with > file?
  5. What does the pipe operator | connect, and does it carry stderr?
  6. Why does sudo echo 'text' > /etc/file fail, and how do you fix it?

Knowledge Check — Answers

  1. 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.
  2. > overwrites the file — any existing content is destroyed. >> appends to the file — existing content is preserved.
  3. find /etc -name '*.conf' 2> /dev/null
  4. 2>&1 means "send stderr to wherever stdout is currently pointing." Order matters because the shell processes redirections left to right. > file 2>&1 first points stdout at the file, then points stderr at stdout — so both go to the file. 2>&1 > file first points stderr at the screen (where stdout is before the redirect), then redirects stdout to the file — leaving stderr on screen.
  5. 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>&1 before the pipe.
  6. 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

  1. 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.
  2. > overwrites; >> appends. Use >> when you need to preserve existing file content. Use 2> to capture errors separately and 2> /dev/null to discard them.
  3. 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 with 2>&1 to include it.
  4. Write > file 2>&1 — not the other way around. Redirect stdout first, then point stderr at stdout. Use sudo tee when writing to root-owned files from a pipeline.

Graded Lab

  • Redirect the output of date to /tmp/mydate.txt, then append a second date output — 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.txt and stderr to /tmp/conf-errors.txt simultaneously
  • Use a pipeline with grep, sort, and uniq -c to count how many accounts in /etc/passwd use each login shell
  • Use tail -f /var/log/messages | grep -i error in one terminal while generating activity in another — observe filtered live output
  • Use echo piped to sudo tee -a to append a comment line to /etc/hosts
RHCSA Objective

"Use input-output redirection (>, >>, |, 2>, etc.)" — Redirection appears in almost every other exam task. Fluency here multiplies your effectiveness across the entire exam.