Redirection and Pipes on Linux

With the > symbol you can forward the output of a command to a file (output redirection), with the < symbol you can use a file as input for a command (input redirection).

By using a pipe symbol, | you can also redirect the output similar to the < or >. With a pipe, you can also combine or link the output of several commands using the output of one command as input for the next command. In contrast to the other redirection symbols > and <, the use of the pipe is not constrained to files.

Examples (Redirection):

1) To write the output of a command like ls to a file, enter

ls -l > filelist.txt

This creates a file named filelist.txt that contains a list of the contents  of your current directory as generated by the ls command. However, if a file named filelist.txt already exists, this command will overwrite the existing file. To prevent this, use >> instead of >.

    ls -l >> filelist.txt

will simply appends the output of the ls command to an already existing file named filelist.txt. If the file does not exist, it is created.

2) Redirection also works the other way round. Instead of using the standard input from the keyboard for a command, you can use a file as input:

    sort < filelist.txt

This will force the sort command to get its input from the contents of filelist.txt. The result is shown on the screen. Of course, you can also write the result into another file, using a combination of redirections:

    sort  < filelist.txt > sorted_filelist.txt

Example (Pipe):

If a command generates a lengthy output, like ls -l may do, it may be useful to pipe the output to a viewer like less to be able to scroll through the pages. To do so, enter

    ls -l | less

The list of contents of the current directory is shown in less.

The pipe is also often used in combination with the grep command in order to search for a certain string in the output of another command. For example, if you want to view a list of files in a directory which are owned by the user tux, enter

    ls -l | grep tux

A longer example would be something like;

grep "SMTP connection from" /var/log/exim_mainlog |grep "connection count" |awk '{print $7}' |cut -d ":" -f 1 |cut -d "[" -f 2 |cut -d "]" -f 1 |sort -n |uniq -c | sort -n

this command will search through the /var/log/exim_mainlog and pull all the IPs in all the entries and line them up in an ascending order. So, you can see how the pipe symbol will take the output from one command and use it in the next and so on.


I am a g33k, Linux blogger, developer, student and Tech Writer for My passion for all things tech drives my hunt for all the coolz. I often need a vacation after I get back from vacation....

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.