How to Use Pipe in Bash: Simple Guide with Examples
In Bash, the
| symbol is called a pipe and it connects the output of one command directly as input to another command. This allows you to combine simple commands to perform complex tasks efficiently without creating temporary files.Syntax
The pipe symbol | is placed between two commands. The first command's output flows into the second command as input.
- command1: Produces output.
- |: Connects output of command1 to input of command2.
- command2: Receives input from command1 and processes it.
bash
command1 | command2
Example
This example shows how to list files in a directory and count how many files there are using a pipe.
bash
ls -1 | wc -lOutput
7
Common Pitfalls
One common mistake is to forget that the pipe passes only the standard output, not errors. So if the first command fails and sends errors, the second command may get no input.
Also, some commands buffer output, so you might not see immediate results when piping.
bash
cat nonexistentfile | wc -l # This shows no lines because cat fails and sends error to stderr, not stdout. # Correct way to include errors: cat nonexistentfile 2>&1 | wc -l
Output
0
1
Quick Reference
|: Connects output of one command to input of another.- Only standard output (stdout) is passed through the pipe.
- Use
2>&1to include error output (stderr) in the pipe. - Multiple pipes can be chained to connect several commands.
Key Takeaways
Use
| to send output of one command as input to another in Bash.Pipes only pass standard output, not error messages by default.
Chain multiple pipes to combine several commands efficiently.
Use
2>&1 to include error output in the pipe if needed.Pipes help avoid temporary files and make scripts cleaner and faster.