Skip to main content
Bash Scripting – Complete Beginner to Advanced Guide
CHAPTER 09 Intermediate

Input, Output, and Redirection

Updated: May 16, 2026
30 min read

# CHAPTER 9

Input, Output, and Redirection

1. Introduction

The Unix terminal is not just a screen; it is a highly sophisticated data plumbing system. When you execute a command, data flows through invisible pipes. If a command succeeds, it sprays "Success" data out of one pipe. If the command fails, it sprays "Error" data out of a completely different pipe. By default, both pipes simply dump their data onto your monitor. As an automation engineer, you cannot allow your scripts to spew messy data onto the screen where it is instantly lost. You must control the plumbing. In this chapter, we will master the three standard streams of Unix (stdin, stdout, stderr), learn to permanently log data into text files using Redirect Operators (> and >>), banish unwanted errors to the /dev/null black hole, and chain commands together using the Pipe (|).

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define the three standard data streams: Standard Input (0), Standard Output (1), and Standard Error (2).
  • Redirect standard output to permanently overwrite or append text files (> and >>).
  • Segregate and redirect error messages into dedicated error log files using 2>.
  • Suppress unwanted terminal output by redirecting data into /dev/null.
  • Chain multiple discrete commands into a single data-processing workflow using the Pipe (|) operator.

3. The Three Standard Streams

Every program running in the Unix terminal utilizes three distinct data pathways, numbered 0, 1, and 2.
  1. 1. stdin (Standard Input - Channel 0): The data flowing INTO the program (e.g., typing on the keyboard).
  1. 2. stdout (Standard Output - Channel 1): The normal, successful text flowing OUT of the program.
  1. 3. stderr (Standard Error - Channel 2): The error and failure messages flowing OUT of the program.

4. Output Redirection (> and >>)

By default, Channel 1 (stdout) prints to your monitor. You can redirect that flow of water into a bucket (a text file) using the Greater-Than symbol.

1. Overwrite (>):

sh
123
# The output of echo goes IN to the text file.
# WARNING: If the file already exists, it is instantly ERASED and overwritten!
echo "Deployment successful." > report.txt

2. Append (>>): In administrative scripting, you usually want to maintain a continuous history log. You use double arrows to *append* data to the absolute bottom of the file, safely preserving the older data.

sh
12
echo "Server Rebooted." >> history.log
echo "Database Started." >> history.log

5. Error Redirection (2>)

If you type ls /directorythatdoesnotexist, Unix prints an error. If you try to log that error by typing ls /fake_dir > log.txt, it fails. The error still prints to the screen, and the text file remains completely blank. Why? Because > only redirects Channel 1 (stdout). Errors flow through Channel 2 (stderr). To catch errors, you must explicitly tell the shell to redirect Channel 2.
sh
123456
# Redirect ONLY the errors into an error log
ls /fake_dir 2> errors.txt

# Pro-Tip: Merge both streams! Send Channel 2 to the exact same place as Channel 1
# (This is standard practice for cron job logging)
./my_script.sh > full_output.log 2>&1

6. The Black Hole (/dev/null)

Sometimes a command generates massive amounts of verbose output or permission errors that you simply do not care about. You don't want to see it, and you don't want to waste hard drive space logging it. You redirect the plumbing into /dev/null. This is a special virtual file in Unix that acts as a black hole. Any data sent here is instantly destroyed.
sh
12
# Search the entire hard drive for a file, but throw all the "Permission Denied" errors into the trash
find / -name "secret.txt" 2> /dev/null

7. The Pipe Operator (|)

Redirection (>) sends data into a *file*. The Pipe (|) sends data into *another command*. This allows you to filter and transform massive amounts of data in a single line of execution.
sh
12345
# Grab the massive output of all running processes, and PIPE it into 'grep' to only show SSH
ps aux | grep "sshd"

# Read a 50,000 line log file, and PIPE it into 'tail' to only view the bottom 5 lines
cat /var/log/syslog | tail -n 5

8. Diagrams/Visual Suggestions

*Visual Concept: The Terminal Plumbing System* Draw a machine block labeled Command (e.g., ping). Draw a funnel entering the left side labeled stdin (0). Draw two pipes exiting the right side:
  • A Blue pipe labeled stdout (1). Show it utilizing a > valve to dump water into a file icon labeled log.txt.
  • A Red pipe labeled stderr (2). Show it utilizing a 2> valve to dump red water into a trash can icon labeled /dev/null.
This visual permanently solidifies the separation of data streams.

9. Best Practices

  • Never > in Production Logs: The single most destructive typo an administrator can make is using > instead of >> when targeting a production log file. Typing echo "Event" > apache.log instantly annihilates years of forensic web server history. Train your fingers to default to >> appending.

10. Common Mistakes

  • Syntax Order Matters (2>&1): When combining streams, the order of redirection is strictly enforced by the shell. You must type command > log.txt 2>&1. If you type command 2>&1 > log.txt, it will fail because you attempted to redirect channel 2 into channel 1 *before* channel 1 was actually pointing at the text file.

11. Mini Project: The Silent Connectivity Logger

Let's build a script that tests internet connectivity quietly, only logging the time when it fails.
  1. 1. nano net_monitor.sh
  1. 2. Write the code:
sh
12345678910111213141516171819
#!/bin/sh

LOG_FILE="/tmp/network_drops.log"

echo "Running network diagnostic (Silent Mode)..."

# Ping Google once. We do not care about the text output, so we dump stdout to the black hole.
# We also dump stderr to the black hole just in case.
ping -c 1 8.8.8.8 > /dev/null 2>&1

# Check the exit code of the ping command
if [ $? -ne 0 ]; then
    # It failed! Append a timestamp to the error log.
    CURRENT_TIME=$(date +"%Y-%m-%d %H:%M:%S")
    echo "[$CURRENT_TIME] CRITICAL: Network connection failed!" >> "$LOG_FILE"
    echo "Network failure detected and logged."
else
    echo "Network is healthy. No logs created."
fi
  1. 3. Run it. You have built an automated diagnostic tool that intelligently manages its own data streams.

12. Practice Exercises

  1. 1. Contrast the mechanical operation of the > operator versus the >> operator. In what specific administrative scenario would utilizing > cause catastrophic data loss?
  1. 2. Explain the fundamental purpose of the /dev/null file within the Unix architecture. Provide a practical scripting example demonstrating its utility.

13. MCQs with Answers

Question 1

A system administrator executes a script without sudo privileges. The terminal output is immediately flooded with dozens of "Permission denied" error messages. Which redirection operator must be utilized to isolate ONLY these error messages and route them into a file named errors.txt while keeping standard output on the screen?

Question 2

When constructing a complex command-line workflow, which operational character is utilized to intercept the standard output (stdout) of one program and pass it directly into the standard input (stdin) of an entirely different program?

14. Interview Questions

  • Q: A developer brings you a shell script containing the execution line ./deploydatabase.sh > deployment.log 2>&1. Explain in precise technical detail exactly what the 2>&1 syntax is accomplishing regarding Linux data streams.
  • Q: Differentiate between the functionality of the Redirection Operator (>) and the Pipe Operator (|). Why can you not use a pipe to send the output of a command directly into a .csv text file?
  • Q: Walk me through the exact terminal syntax required to execute a highly verbose compilation script named build.sh, safely discard all normal standard operational output, but capture all critical compilation errors into a file named buildfailures.log.

15. FAQs

Q: Can I pipe data into a file instead of redirecting it? A: You cannot use a pipe | directly into a file, but you can pipe into a special utility called tee. If you execute echo "System Check" | tee report.txt, the tee command acts as a literal T-junction in the plumbing: it prints the text to your monitor AND simultaneously saves it to the text file!

16. Summary

In Chapter 9, we seized absolute control over the Unix data plumbing architecture. We identified the three foundational streams (stdin, stdout, stderr), mastering the ability to segregate successful operational data from catastrophic error reporting. We utilized the > and >> operators to permanently serialize transient terminal outputs into forensic text files, strictly adhering to the append syntax to safeguard historical logs. We deployed the /dev/null black hole to ruthlessly suppress operational noise, and finally, we engineered multi-stage pipelines using the Pipe (|), seamlessly stitching discrete commands into unified data processing chains.

17. Next Chapter Recommendation

You can capture and route standard text efficiently. But what if you need to manipulate highly complex text strings, or store massive lists of data in a single variable? Proceed to Chapter 10: Arrays and String Manipulation.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·