Shell Programming Blog Shell Programming Blog

Sunday, 21 October 2012

Linux Bash Scripting: Standard file descriptors STDIN, STDOUT and STDERR and input/ouput redirection

Unknown | 08:52 | |


 Bash Linux Unix shell scripting

Linux system handles every object as a file. This includes input and output processes also. The linux identifies each file using a file descriptor.

What is a file descriptor?
A file descriptor is a non negative integer which uniquely identifies the open files. Each process can have upto 9 open files at a time. The bash shell reserved three file descriptors(0, 1 and 2) for special purposes.



Linux Standard File Descriptors
File descriptor
Abbreviations
Description
0
STDIN
Standard Input
1
STDOUT
Standard output
2
STDERR
Standard Error






The above three file descriptor controls the input and output of your scripts. The shell uses these descriptors to assign the input and output to appropriate locations (default is the monitor or the terminal).  Now let us see each one in detail.

STDIN

The STDIN file descriptor refers the keyboard in the terminal environment. So, the Linux will read the input from keyboard always unless it is changed.

 

The above “cat” command accepts input from the keyboard.  If you want to force the “cat” command to accept the input other than STDIN, you can use STDIN redirect symbol (<).



STDOUT

The STDOUT descriptor refers to the standard output of the shell (i.e. the monitor). So, the Linux directs all the output to the monitor unless it is changed.



You can also append the data to a file by using the >> symbol.



But whenever the command produces an error, it will be displayed in the monitor even if the output is redirected to a file. That is because the error details have a separate file descriptor (STDERR).

STDERR

By default the STDERR descriptor refers to monitor.



The above example shows that the error message is displayed even after the output is redirected to the file called test. If you want to redirect the error message to some other file, you can do it as below.



If you want to redirect the output and the error message to different files, you can do as below.



If you want to redirect both the error message and the output to the same file, you can use the & operator as shown below.

0 Comments:

   

Post a Comment

Don't just read and walk away, Your Feedback Is Always Appreciated. I will try to reply to your queries as soon as time allows.

Note:
1. If your question is unrelated to this article, please use our Facebook Page.
2. Please always make use of your name in the comment box instead of anonymous so that i can respond to you through your name and don't make use of Names such as "Admin" or "ADMIN" if you want your Comment to be published.
3. Please do not spam, spam comments will be deleted immediately upon my review.

Regards,
Mohamed Abubakar Sittik A

 

Shell Programming Copyright © 2012 Shell Programming theme is Designed by Abusittik, Shell Programming