โ† Linux Command Line

Pipes and Redirection

~290 words ยท 2 min read

Three streams

Every command has three streams wired to it:

  • stdin (0) โ€” input, usually your keyboard
  • stdout (1) โ€” normal output, usually the screen
  • stderr (2) โ€” error messages, also the screen

Redirection

Send output to a file instead of the screen:

echo "hello" > file.txt     # overwrite (creates or truncates)
echo "world" >> file.txt    # append (adds to the end)
cat file.txt                # hello
                            # world

> replaces the file. >> adds to it. Choose based on whether you want to keep what was already there.

Pipes

A pipe | connects one command's stdout to the next command's stdin, letting you chain small tools into a pipeline:

cat access.log | grep "404" | sort | uniq -c | sort -rn | head -10

Read it left to right: take the file, keep lines containing "404", sort them, count duplicates, sort by count descending, show the top 10.

Handling errors

Redirect stderr separately by its number:

find / -name "*.log" 2>/dev/null        # throw errors away
cmd > out.txt 2>&1                       # combine stdout + stderr into one file
cmd 2> errors.txt                        # save only errors
/dev/null is a black hole โ€” anything you send there disappears. Perfect for silencing noisy errors.

Everyday text tools

  • grep "pattern" โ€” filter lines matching a pattern
  • sort โ€” alphabetize
  • uniq -c โ€” collapse adjacent duplicates (pipe through sort first)
  • head -n 20 / tail -n 20 โ€” first / last N lines
  • wc -l โ€” count lines