Menu
Coddy logo textTech

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 -l

The 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 -5

This 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 -3

This shows detailed information for just the first few items in a directory. The pipe transforms two simple commands into a more powerful operation.

challenge icon

Challenge

Easy

Use a pipe to display only the first 4 lines of messages.txt in a single command.

Run a command that:

  • Uses cat to read messages.txt
  • Pipes the output to head -4 to show only the first 4 lines

Hint: Chain the two commands together using the | symbol. The output of cat becomes the input for head.

Cheat sheet

Pipes (|) connect commands by sending the output of one command as input to another.

Count files in a directory:

ls | wc -l

Display the first few lines of a file:

cat longfile.txt | head -5

Show detailed information for the first few directory items:

ls -l | head -3

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals