How to Send a Command's Output to Another Command with a Pipe in bash and zsh
Many terminal tasks take two steps: list something, then count it, sort it or filter it. A pipe, |, sends one command's output straight into the next command, with no file in between. This guide counts the files in a folder, with real output from zsh 5.9 and bash 3.2.
Syntax
<command1> | <command2>
| Part | What it means |
|---|---|
<command1> | Runs first. Its output goes into the pipe instead of to the screen |
| | The pipe |
<command2> | Reads that output as its input |
The bash manual: "The output of each command in the pipeline is connected via a pipe to the input of the next command. That is, each command reads the previous command’s output."
Prerequisites
- zsh or bash. This guide uses zsh 5.9, the default shell on macOS, and checks every command in bash 3.2 too.
Step 1: Count the Files in a Folder
The folder holds three empty files:
ls
draft.txt notes.txt report.txt
wc -l counts lines. Pipe the listing into it:
ls | wc -l
3

ls sent the three names into the pipe, and wc -l counted 3 lines, one per file. The spaces before the 3 are how macOS's wc lines up its numbers. bash printed the same count.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Piping into a command that doesn't read its input: ls | echo | echo prints only its own arguments, so it printed an empty line | Pipe into commands that read their input, such as wc, sort, head or grep |
| Expecting errors to go through the pipe | Only output does: ls missing.txt | wc -l printed the error on the screen and a count of 0 | Send errors along too with 2>&1 before the |: ls missing.txt 2>&1 | wc -l counted 1 |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| The second command prints nothing useful | It doesn't read its input | Check that it reads its input, as wc and sort do |
FAQ
Can I chain more than two commands?
Yes. ls | sort -r | head -n 1 sorted the names in reverse and kept the first, report.txt. Each command reads what the one before it printed.
Why do errors skip the pipe?
A pipe carries standard output only. The zsh manual: "Where commands are separated by ‘|’, the standard output of the first command is connected to the standard input of the next."
Conclusion
ls | wc -l sent the listing into wc -l, which counted 3 files. Put | between two commands whenever the second should work on what the first prints.
Additional Resources
- Pipelines — pipes in the bash manual.
- zsh: Shell Grammar — pipelines in zsh.
- wc invocation —
wcand its options in GNU Coreutils.
