3.8.3 Using pipes

Rate this post

Next: 3.8.4 Non-destructive redirection Up: 3.8 UNIX Plumbing Previous: 3.8.2 Redirecting input and

  We’ve already demonstrated how to use sort as a filter. However, these examples assumed that you had data in a file somewhere, or were willing to type the data to standard input yourself. What if the data you wanted to sort came from the output of another command, such as ls? For example, using the -r option with sort sorts the data in reverse-alphabetical order. If you wanted to list the files in your current directory in reverse order, one way to do it would be:

/home/larry/papers# ls english-list history-final masters-thesis notes

/home/larry/papers# ls > file-list

/home/larry/papers# sort -r file-list notes masters-thesis history-final english-list


Here, we saved the output of ls in a file, and then ran sort -r on that file. But this is unwieldy and causes us to use a temporary file to save the data from ls.

    The solution is to use pipelining. Pipelining is another feature of the shell which allows you to connect a string of commands in a « pipe », where the stdout of the first command is sent directly to the stdin of the second command, and so on. Here, we wish to send the stdout of ls to the stdin of sort. The « | » symbol is used to create a pipe:

/home/larry/papers# ls sort -r notes masters-thesis history-final english-list


This command is much shorter, and obviously easier to type.

Another useful example—using the command

/home/larry/papers# ls /usr/bin is going to display a long list a files, most of which will fly past the screen too quickly for you to read them. Instead, let’s use more to display the list of files in /usr/bin.

Lire aussi...  C editing with VIM HOWTO

/home/larry/papers# ls /usr/bin more Now you can page down the list of files at your own leisure.

But the fun doesn’t stop here! We can pipe more than two commands together. The command head is a filter which displays the first lines from an input stream (here, input from a pipe). If we wanted to display the last filename in alphabetical order in the current directory, we can use:

/home/larry/papers# ls sort -r head -1 notes


where head -1 simply displays the first line of input that it receives (in this case, the stream of reverse-sorted data from ls).  

Next: 3.8.4 Non-destructive redirection Up: 3.8 UNIX Plumbing Previous: 3.8.2 Redirecting input and

Matt Welsh