Skip to main content

How to Send a Command's Output to Another Command with a Pipe in bash and zsh

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
<command1> | <command2>
PartWhat 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:

Terminal
ls
Output
draft.txt notes.txt report.txt

wc -l counts lines. Pipe the listing into it:

Terminal
ls | wc -l
Output
3

zsh running ls, which lists three files, then ls | wc -l, which prints 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​

MistakeWhat happensDo this instead
Piping into a command that doesn't read its input: ls | echoecho prints only its own arguments, so it printed an empty linePipe into commands that read their input, such as wc, sort, head or grep
Expecting errors to go through the pipeOnly output does: ls missing.txt | wc -l printed the error on the screen and a count of 0Send errors along too with 2>&1 before the |: ls missing.txt 2>&1 | wc -l counted 1

Troubleshooting​

SymptomLikely causeFix
The second command prints nothing usefulIt doesn't read its inputCheck 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​