Skip to Content
This project is a work in progress. If you have any questions or suggestions, feel free to contact me.

Pipe (|) in Linux

What is a pipe?

In Unix/Linux, a pipe (|) is used to connect the output of one command to the input of another. It allows command chaining, enabling small programs to work together efficiently — a core concept of the Unix philosophy.


Syntax

command1 | command2
  • command1: produces output (stdout)
  • command2: reads input (stdin) from command1’s output

Common Examples

View log and filter

cat /var/log/syslog | grep "error"
  • cat: displays the log
  • grep: filters lines containing “error”

Count files

ls -1 | wc -l
  • ls -1: lists one file per line
  • wc -l: counts number of lines (i.e., files)

Sort and remove duplicates

cat file.txt | sort | uniq
  • sort: sorts lines
  • uniq: removes consecutive duplicates

Chain multiple commands

ps aux | grep apache | awk '{print $2}' | xargs kill
  • Lists processes
  • Filters those with “apache”
  • Extracts PID
  • Kills the processes

Best Practices

  • Avoid using cat unnecessarily. Example:

    grep "error" file.txt # better than cat file.txt | grep "error"
  • Pipes can be chained for multiple processing steps.

  • Combine with redirection for logging output:

    command1 | command2 > output.txt

Why use pipes?

  • Save time and typing
  • Avoid temporary files
  • Let small tools do one job each and work together
  • Powerful for automation and scripting
Last updated on