Intermediate โฑ 20 min Lesson 5 of 13

๐Ÿ”€ Input & Output

Master redirection, pipes, stdin/stdout/stderr, and here documents.

Streams & Redirection

Every program in Linux has three standard data streams, each identified by a file descriptor number:

  • stdin (0): Standard input โ€” data going into a command (usually from the keyboard).
  • stdout (1): Standard output โ€” normal output from a command.
  • stderr (2): Standard error โ€” error messages from a command.

Output Redirection

Redirection lets you send the output of a command to a file instead of the screen.

bash
# > overwrites the file (creates it if it doesn't exist)
echo "Hello" > output.txt

# >> appends to the file
echo "World" >> output.txt

# Redirect stderr to a file
ls /nonexistent 2> errors.txt

# Redirect both stdout and stderr to the same file
command &> all_output.txt
# or
command > output.txt 2>&1

Input Redirection

bash
# Feed a file into a command
sort < unsorted.txt

# Combine input and output redirection
sort < unsorted.txt > sorted.txt
๐Ÿ’ก Tip: Think of > as an arrow pointing where the output should go. > sends stdout to a file; 2> sends stderr to a file.

Pipes

Pipes (|) connect the stdout of one command to the stdin of the next. They're one of the most powerful features in Bash.

bash
# Count files in a directory
ls | wc -l

# Find a process
ps aux | grep nginx

# Chain multiple pipes
cat access.log | grep "404" | sort | uniq -c | sort -rn | head

The tee Command

tee reads from stdin and writes to both stdout and a file simultaneously. It's like a T-junction in plumbing.

bash
# Display output AND save it to a file
ls -la | tee listing.txt

# Append instead of overwrite
echo "new line" | tee -a logfile.txt

/dev/null โ€” The Black Hole

/dev/null is a special device that discards all data written to it. It's useful when you want to suppress output.

bash
# Discard stdout
command > /dev/null

# Discard stderr
command 2> /dev/null

# Discard everything
command &> /dev/null

Here Documents

A here document lets you pass multi-line input to a command inline.

bash
cat <<EOF
This is line one.
This is line two.
Variable expansion works: $USER
EOF

# Here string (single line)
grep "hello" <<< "hello world"
โš ๏ธ Warning: The ending delimiter (e.g., EOF) must appear on its own line with no leading spaces (unless you use <<- which strips leading tabs).

Try It Yourself

Terminal

Summary

You've learned the three standard streams, output/input redirection with >, >>, and <, how to pipe commands together with |, the tee command, /dev/null, and here documents. These concepts are fundamental to everything in Bash scripting.

๐Ÿงช Test Your Knowledge

Answer the questions below to check your understanding of this lesson.