How to use pipes and redirection

Overview

Commands normally read standard input and write standard output plus standard error. Pipes and redirection let you connect these streams without copying text manually.

Examples

ls -la | less
grep -i 'error' app.log | tail -n 20
printf '%s\n' 'hello' > message.txt
date >> activity.log
command 2> errors.log
command > all.log 2>&1

Operators

  • | sends one command's standard output to the next
  • > overwrites a file with standard output
  • >> appends standard output
  • < reads standard input from a file
  • 2> redirects standard error
  • tee file displays output and writes a copy

Safety

A single > truncates an existing file before the command runs. Double-check destination paths, especially when using sudo.

A pipe passes text, not files themselves. Inspect each command separately before building a long pipeline.