Chaining Two Commands
Part of the Fundamentals section of Coddy's Terminal journey — lesson 44 of 82.
Now that you understand what a pipe does, let's see how to use it effectively with two commands. The key is choosing commands that work well together — where the output of the first makes sense as input for the second.
A common pairing is ls with wc -l to count files:
ls | wc -lThe ls command lists files (one per line), and wc -l counts those lines. The result is the number of files in the current directory.
Another useful combination is cat with head to preview a file:
cat longfile.txt | head -5This displays only the first 5 lines of the file. You could also use head -5 longfile.txt directly, but piping becomes essential when the first command generates output that isn't simply reading a file.
For example, combining ls -l with head:
ls -l | head -3This shows detailed information for just the first few items in a directory. The pipe transforms two simple commands into a more powerful operation.
Challenge
EasyUse a pipe to display only the first 4 lines of messages.txt in a single command.
Run a command that:
- Uses
catto readmessages.txt - Pipes the output to
head -4to show only the first 4 lines
Hint: Chain the two commands together using the
|symbol. The output ofcatbecomes the input forhead.
Cheat sheet
Pipes (|) connect commands by sending the output of one command as input to another.
Count files in a directory:
ls | wc -lDisplay the first few lines of a file:
cat longfile.txt | head -5Show detailed information for the first few directory items:
ls -l | head -3Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Directories
Create A DirectoryCopy A DirectoryMove And Rename A DirectoryDelete A DirectoryRecap - Directory Operations7File Content
Head And TailWord CountSort CommandUnique CommandGrep BasicsGrep With FlagsRecap - Text Detective2Navigation
Print Working DirectoryList FilesChange DirectoryAbsolute vs Relative PathsHome And Root DirectoryRecap - Find Your Way8Redirection
Standard OutputOverwrite To A FileAppend To A FileStandard InputStandard ErrorRecap - Log Builder6Wildcards And Patterns
The Star WildcardThe Question Mark WildcardBracket WildcardsCombining WildcardsRecap - Selective Operations9Piping
What Is A PipeChaining Two CommandsChaining Multiple CommandsPipe With GrepRecap - Data Pipeline