A pipe bridges two processes together. The pipe, written with the
| character, connects the output of one command to the input of the second. It’s one of the fundamental building blocks of a Unix shell.
A very basic example is using
cat to feed the contents of a file to the word count tool
$ cat <filename> | wc
Just in case you didn’t know these commands:
catprints the contents of a file.
wccounts all the lines, words and bytes it is fed.
Another often-used version is
wc -l, which only counts the number of lines in a file.
Let’s try this. First, create a file called
words.txt with this content:
hello world python ninja are you ? 3 2 1
Then run this command:
$ cat words.txt | wc -l
The output should be 10 since there are 10 lines in the file. Another example is using
sort to sort the words in your file:
$ cat words.txt | sort ? are hello ninja python world you 1 2 3
As we can see, all the words from
words.txt are fed to
sort, which sorts them. Punctuation first, then numbers and then letters.
Alright. Here’s one last, questionable example of using pipes. There’s this awesome tool called
cowsay. It generates an ASCII picture of a cow saying something that you feed it:
$ echo "Are we going to learn anything useful?" | cowsay ________________________________________ < Are we going to learn anything useful? > ---------------------------------------- \ ^__^ \ (oo)\_______ (__)\ )\/\ ||----w | || ||
This is the stuff that will make a lasting impression on your colleagues.