How to use pipes and redirection in Linux

· Category: Linux

Short answer

Pipes (|) send one command's output to another's input; redirects (>, <>, 2>) write output to files or streams.

Steps

  1. Pipe output:
cat log.txt | grep error
  1. Redirect stdout to file:
echo "hello" > file.txt
  1. Append to file:
echo "world" >> file.txt
  1. Redirect stderr:
command 2> error.log
  1. Both stdout and stderr:
command >> log.txt 2>&1

Tips

  • tee writes to both stdout and a file: command | tee output.txt.
  • /dev/null discards output: command > /dev/null 2>&1.
  • Use xargs to convert piped text into command arguments.

Common issues

  • > overwrites existing files; use >> to append.
  • Order matters: 2>&1 must come after the stdout redirect.