Bash Pipes
A pipe sends the output of one command into the next command. The next command then works on that output.
Count words through a pipe
The wc -w command counts words in its input. The pipe sends the echo output into wc.
echo "one two three" | wc -wCount files through a pipe
The ls command lists the files in the current folder. Only the script file sits in this folder, so the count is 1.
ls | wc -lCount file lines through a pipe
The cat command prints the file contents. The pipe sends those three lines into wc -l.
echo "apple" > list.txt
echo "banana" >> list.txt
echo "cherry" >> list.txt
cat list.txt | wc -lExample
echo "apple pie" > menu.txt
echo "banana split" >> menu.txt
echo "cherry tart" >> menu.txt
cat menu.txt | wc -l
cat menu.txt | wc -wKey points
- The | symbol is called a pipe.
- A pipe connects the output of one command to the next command.
- The wc -l command counts lines in its input.
- The wc -w command counts words in its input.
- Commands in a pipe run from left to right.
In this example, three echo lines build a small menu file. The first pipe sends the file into wc -l and counts three lines. The second pipe sends the file into wc -w and counts six words.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does a pipe do between two commands?