Wednesday, July 25, 2012

Piping input and Redirection - Linux

A program interacts with two essential principles: input and output. The Linux command line allows us to skew these principles in something called IO redirection and piping, which is a very helpful thing to be able to do. If you already know C++ then your knowledge of the << and >> operators will come in handy. 

About
 Redirection
  Redirection allows you to move output somewhere else. For instance, dmesg > file.txt would move the 
  would move the output of "dmesg" into file.txt instead of to standard output. Input redirection is like output
  redirection, but it gets its input from somewhere else.
  
 Piping
  Piping is using one program's output as another's input.

How to use IO redirection and piping
 We will be using dmesg and espeak for our example. If you cannot get a hold of espeak, it is a program that outputs text given to it as an argument as audio.

Output Redirection
The greater than symbol, ">", is used to shoot output into somewhere else, usually a file. An example would be ls > file.txt which puts the output of "ls" into file.txt.

Input Redirection
Much like >, < is used to redirect input. Input Redirection can be confusing. It uses a file or some other source to get the input for a program. An example would be espeak < file.txt. This will use file.txt as input for espeak.

Combining IO redirection
The following example is going to gather input from a file, get the output, and put it in another file.
 wc < my_files > wc_output. This calls wc on my_files and puts it to wc_output. It would look like this with parenthesis: (wc < my_file)>wc_output. To use this as input, you would need to do program < wc < my_files > wc_output. That is overly complicated, so we will use piping.

Piping
Piping is a very important concept. It uses the pipe bar ( | ) to use the output of one program as input for another. So far we have used ls to put its output in a file and then used espeak to read that file. Now we are going to combine the steps. ls | espeak. What that line means is that the output of ls is going to be piped to espeak as input. Of course, you can still use IO redirection to get espeak's output into some file by using >.
  

No comments:

Post a Comment