A quick look at redirection in the bash shell.

The bash shell allows the user to redirect output from one application to another or to a file. This is very useful when you are building a one liner script to perform a certain action.

Here is a simple redirection.

ls > ls.out

This redirects the output of the ls command to a file that contains the list of files.

If you use this syntax:

gedit 2> /dev/null

Then the errors output by the program will be redirected to /dev/null.

Another use for redirection is to redirect the output of one program to another to perform a certain task. This one is piping the output of the ls command to grep to find a certain file.

homer@deusexmachina ~ $ ls -hula | grep ".cshrc"
-rw-------  1 homer homer 2.1K Apr 29 19:18 .cshrc

You may also use the redirection character in the reverse direction to direct the output of a file into the cat command.

homer@deusexmachina ~ $ cat < missfont.log 
mktexpk --mfmode / --bdpi 600 --mag 1+0/600 --dpi 600 ec-lmri10
mktexpk --mfmode / --bdpi 600 --mag 1+0/600 --dpi 600 ec-lmbx12
mktexpk --mfmode / --bdpi 600 --mag 1+0/600 --dpi 600 ec-lmr7
mktexpk --mfmode / --bdpi 600 --mag 1+120/600 --dpi 720 ec-lmbx12
mktexpk --mfmode / --bdpi 600 --mag 1+437/600 --dpi 1037 ec-lmbx12
mktexpk --mfmode / --bdpi 600 --mag 1+0/600 --dpi 600 lmsy10
mktexpk --mfmode / --bdpi 600 --mag 1+0/600 --dpi 600 ec-lmbx10
mktexpk --mfmode / --bdpi 600 --mag 2+44/600 --dpi 1244 ec-lmbx12
mktexpk --mfmode / --bdpi 600 --mag 1+0/600 --dpi 600 ec-lmr12
mktexpk --mfmode / --bdpi 600 --mag 1+0/600 --dpi 600 ec-lmr17
mktexpk --mfmode / --bdpi 600 --mag 1+0/600 --dpi 600 ec-lmr10

This is a more complex piping example that shows how to build a one-liner script.

homer@deusexmachina ~ $ host yahoo.com | awk '/ has address / { print $4 }' | cut -d " " -f14-
98.138.253.109

This is a similar equivalent that will perform the same task.

homer@deusexmachina ~ $ ifconfig eth1 | awk '/inet/ { print $2 } ' | sed -e s/addr://
10.10.1.2

This is a strange way to perform redirection; but this does actually work.

homer@deusexmachina ~ $ ps | echo $0 out2.txt
bash out2.txt

Printing out the file for evidence.

homer@deusexmachina ~ $ cat out.txt 
  PID TTY          TIME CMD
 8530 pts/0    00:00:00 bash
 9046 pts/0    00:00:00 ps

Try this yourself!

No comments have been made. Use this form to start the conversation :)

Leave a Reply