Piping and Redirecting


The shell is designed by default to receive input from the keyboard (standard input) and to output to the screen (standard output). There are many occasions however when you may need to have output from the shell sent to different places. This is where piping comes in. Piping essentially redirects output from the shell to another programme, shell command or file. A simple example would be when you ask the shell to list all the files in a large directory. If there are so many files they will disappear off the top of the screen and no amount of scrolling will allow you to see them again. Piping the output of the list command to less (less is a text reader implimented in the console) however will cause the output to be stored in less and from there you can browse it at will.

If you want to search a directory for a certain file, the exact name of which you don't know, then you can pipe the ls output to grep and let it do the searching for you:

ls –l | grep –i 'flower'


Redirecting output is similar to piping, however the output is sent to a file. To send the list of a directory to the file directorylist.txt use

ls -l > directorylist.txt


If the file directorylist.txt does not exist it will be created. If the file does exist the content will be overwritten. If you want to add the output of ls to the contents of the file then a double redirection is used:

ls -l >> directorylist.txt


This appends the output of ls to the end of the existing file.

Redirection can also be used as input:

sort < directorylist.txt


The above tells the sort command (which sorts data according to the ASCII system) to take the directorylist.txt file as its input. Redirections can be combined:

sort < directorylist.txt > sorteddirectorylist.txt