Pipes

In Linux, pipes connect the standard output of one command to the standard input of another command.

Consider the ls command that was discussed earlier. There are plenty of options available with ls, but what if the contents of a directory stream by too quickly for you to view them?

View the contents of the /etc directory.

ls -al /etc

How do you get a closer look at the output before it moves off the screen?

One way is to pipe the output to a utility called less. Known as a pager, less allows you to view information one page (or screen) at a time.

Use the vertical bar (|) to pipe the commands (as shown in Figure 10-11).

ls -al /etc | less

Now we can view the contents one screen at a time. To move forward a screen, press [Space]; to move back a screen, press [b]; to quit, press [q].

TipHow to Read Your Startup Messages
 

To read startup messages more closely, at a shell prompt, type dmesg | less. You will be able to read the file one screen at a time. To move forward, press the [Spacebar]; to quit, press [Q].

Figure 10-11. Piping Output of ls to less

Actually, pipes have already been introduced in this manual. In previous references to man pages, you used the following command to print them:

man ls | col -b | lpr

Here, the output of man ls is sent to a filter called col with an option of -b to help format the text for the printer. Then that output is sent to the printer using the lpr command.

For another example, type:

grep coffee sneakers.txt | lpr

This will print every line in the sneakers.txt file that mentions the word "coffee" (read more about grep in the section called The grep Command).

The more Command

The main difference between more and less is that more only lets you move forward through a file and less lets you move backwards and forwards.

Let's take a look at the man page for more, but this time, we will open the page using more — by piping man's output to more.

	  man more | more