Linux File Discriptors

The Standard UNIX File Descriptors – Standard Input (stdin), Standard Output (stdout), and Standard Error (stderr). Bash and other modern shell provides I/O redirection facility. There are 3 default standard files (standard streams) open:
[a] stdin – Use to get input (keyboard) i.e. data going into a program.

[b] stdout – Use to write information (screen)

[c] stderr – Use to write error message (screen)

You can look at /usr/include/unistd.h if you forget them:

/* Standard file descriptors.  */
#define STDIN_FILENO    0   /* Standard input.  */
#define STDOUT_FILENO   1   /* Standard output.  */
#define STDERR_FILENO   2   /* Standard error output.  */

Redirecting the standard error stream to a file

The following will redirect program error message to a file called error.log:


$ program-name 2> error.log
$ command1 2> error.log

Redirecting the standard error (stderr) and stdout to file

Use the following syntax:

$ command-name &>file
OR
$ command > file-name 2>&1
Another useful example:
# find /usr/home -name .profile 2>&1 | more

Redirect stderr to stdout

Use the command as follows:

$ command-name 2>&1

Here’s another example:

nohup somescript.sh >/dev/null 2>&1 &

The simple explanation to this is “all output from this script should be pushed into a black hole while the script is being run in the background (& in the end of the command).”  That’s one good way to make a program be really quiet!

More Example


<strong>$ cat &gt; demoscr</strong>
 if [ $# -ne 2 ]
 then
 echo "Error : Number are not supplied"
 echo "Usage : $0 number1 number2"
 exit 1
 fi
 ans=`expr $1 + $2`
 echo "Sum is $ans

Run it as follows:
$ chmod 755 demoscr
$ ./demoscr

Error : Number are not supplied
Usage : ./demoscr number1 number2

$ ./demoscr > er1
$ ./demoscr 5 7

Sum is 12

For first sample run , our script prints error message indicating that you have not given two number.

For second sample run, you have redirect output of script to file er1, since it’s error we have to show it to user, It means we have to print our error message on stderr not on stdout. To overcome this problem replace above echo statements as follows

echo "Error : Number are not supplied" 1>&2
echo "Usage : $0 number1 number2" 1>&2

Now if you run it as follows:
$ ./demoscr > er1
Error : Number are not supplied
Usage : ./demoscr number1 number2

It will print error message on stderr and not on stdout. The 1>&2 at the end of echo statement, directs the standard output (stdout) to standard error (stderr) device.
Syntax:
from>&destination


Sources:

http://www.cyberciti.biz/faq/redirecting-stderr-to-stdout/

http://stackoverflow.com/questions/818255/in-the-bash-shell-what-is-21

http://www.freeos.com/guides/lsst/ch04sec4.html

You may also like