Search This Blog

Wednesday, November 5, 2008

Redirectoin in LINUX ,>,>>

What is Redirection and How Does it Work?

Redirecting the Input or Output of Linux Commands

Another useful bash feature is its ability to redirect the input and output of Linux commands. You can save the results of a command in a file instead of displaying the results on the screen, or you can feed data from a file to a program instead of entering data from the keyboard.Let's look at redirection first. Imagine a fictitious command called nocats that prompts the user for a number and then waits for that many lines of text to be entered before processing them. (The program looks at each input line and pr ints only the ones that do not contain the word cat.)

You could feed the program by entering the data from the console (bold text is your typed input, normal text is console output):

$ nocats 3 Dogs are much better than those other household animals. A cat would never beg for jerky treats. Dogs are pretty stupid, but at least they stick around. Dogs are much better than those other household animals. Dogs are pretty stupid, but at least they stick around.

Or using a text editor, you could put all the input data in a file called stuff and feed the nocats program like this:

% nocats Dogs are much better than those other household animals. Dogs are pretty stupid, but at least they stick around.

The less-than (<) symbol causes the program to get input from the stuff file instead of waiting for keyboard input. The greater-than (>) symbol, on the other hand, redirects output to a file instead of to the console. Thus, the co mmand

% nocats <> bother

will cause the nocats program to read its input from one file (stuff) and write it to another (bother), without the keyboard or console entering the picture. Note that the nocats progra m doesn't know or care about all this redirection. It still thinks it is reading data from the keyboard and writing to the console--but the shell has temporarily reassigned the input and output to files instead of physical devices.

To append to an existing file instead of creating a new one, use two greater-than symbols (>>), as in this example:

zippity > somefile doodah >> somefile

The zippity command runs first, and the output is placed in a new file called somefile. Then doodah runs, and its output is added (appended) to the somefile file.

Note: It's important to remember that piping with a single > symbol will wipe out existing data if the output file already exists.

No comments: