Piping and Re-Direction

Before we move on to learning even more commands, let’s side-track to the topics of piping and re-direction. The basic UNIX philosophy, therefore by extension the Linux philosophy, is to have many small programs and utilities that do a particular job very well. It is the responsibility of the programmer or user to combine these utilities to make more useful command sequences.

 

Piping Commands Together

The pipe character, “|”, is used to chain two or more commands together. The output of the first command is “piped” into the next program, and if there is a second pipe, the output is sent to the third program, etc. For example:

ls -la /usr/bin | less

In this example, we run the command “ls -la /usr/bin”, which gives us a long listing of all of the files in /usr/bin.

Because the output of this command is typically very long, we pipe the output to a program called “less”, which displays the output for us one screen at a time.

 

Redirecting Program Output to Files

There are times when it is useful to save the output of a command to a file, instead of displaying it to the screen. For example, if we want to create a file that lists all of the MP3 files in a directory, we can do something like this, using the “>” redirection character:

ls -l /home/vic/MP3/*.mp3 > mp3files.txt

A similar command can be written so that instead of creating a new file called mp3files.txt, we can append to the end of the original file:

ls -l /home/vic/extraMP3s/*.mp3 >> mp3files.txt