Thursday, April 8, 2010

Redireciton of input and output on linux shell..

Syntax:
linux-command redirection-symbol input/output-file-name

There are three basic redirection operators.
  1. output (>)
    ex: $ ls > dirList.txt
    the output of the ls command will write in dirList.txt if the file is already present then it will be overwritten without any warning.

  2. append (>>)
    To output Linux-commands result to the end of file (append). Note that if file exist , it will be opened and new information will be written to end of file, without losing previous information, And if file is not exist, then new file is created. For e.g. To send output of pstree command to already exist file give command
    ex: $ pstree >> processList.txt

  3. input (<) To take input to Linux-command from file instead of key-board. If file does not exist then you have to give using key-board. ex: ./a.out < input.in
In Linux in C/CPP programming Language keyboard, screen etc are all treated as files. these files are:


































File Name

Discriptor

Use

Example

Stdin

0

Standard Input

Keyboard

Stdout

1

Standard Output

Screen

Stderr

2

Standard Error

Screen
In linux every program has three files associated with it, (when we start our program these three files are automatically opened by the shell). The use of first two files (stdin and stdout) , are already seen by us. The last file stderr is used by our program to print error on screen. Error message can't be redirected, for example the Command $ rm file1.txt > getError.txt will not log the error(rm: cannot remove `file1.txt': No such file or directory) into the file getError.txt in case file1.txt does not present, since output is send to error device. But if still want to log the error, use the discriptor for example $ rm file1.txt 2>getError.txt


No comments:

Post a Comment

Search Ranjeet's Blog