Friday, 24 June 2011

Redirection of standard input/output in Linux


When we type a command on the terminal we get an output corresponding to that command. But suppose we want to store the output to a file or redirect the output directly onto the printer then what should we do?

The answer is simple redirection operators.


In Unix and Unix like systems the everything is associated with a file descriptor from the display on the screen to reading from a socket connection. A file descriptor is a unique number assigned for specific i/o operations. Using the redirections operators, the file descriptor can be redirected to a file or any other output a stream like serial port or printer. Even the input required can be taken in from a file.

But there are three most important file descriptors which are associated with every program of command you work with.


The standard output is associated with with file descriptor 1 which is generally the screen but can be redirected to any other output stream.

Lets discuss how to redirect input and output to and from a file

1. > Redirector Symbol
Syntax:
Linux-command > filename
To output Linux-commands result (output of command or shell script) to file. Note that if file already exist, it will be overwritten else new file is created.


For example:



The ls command list the contents of the directory. The second screenshot shows that the ls output is redirected to a file HomeDirectory.txt in the same directory and therefore there is no output on the screen. Now if we use the cat command to see the contents of the HomeDirectory.txt then you can easily guess that it contains the output of the ls command.

Note: However if use use redirection again to the same file then the file contents will be overwritten.

2.  >> Redirector Symbol
Syntax:
Linux-command >> filename
To output Linux-commands result (output of command or shell script) to END of file. Note that if file exist , it will be opened and new information/data will be written to END of file, without losing previous information/data, And if file is not exist, then new file is created.

For example: If we want to append the output of pwd command to the end of the HomeDirectory.txt



We can see in the second screenshot the output of the pwd command is appended to the HomeDirectory.txt

3. < Redirector Symbol
Syntax:
Linux-command < filename
To take input to Linux-command from file instead of key-board.

For example: We will use HomeDirectory.txt as an input to the tail command.


Th output shows the last 10 lines of the HomeDirectory.txt on standard ouput i.e screen. We can even use the i/o redirection operators together.










No comments:

Post a Comment

Popular Posts