Sunday, April 06, 2008

I/O Redirection in shell or shell scripting

You will come across this situation when you want to run a process in background. Mostly, you want to capture the output or the errors thrown by the process.

As you must be already knowing, three file descriptors are available by default in any programming language. Similar is the case for a shell or shell scripting. The three are standard input (stdin), standard output (stdout) and standard error (stderr). Their corresponding file descriptors are 0, 1 and 2.

You can use these file descriptors while redirecting your input/output.

Syntax for redirection is as follows
# "M" is a file descriptor, which defaults to 1, if not explicitly set.
# "N" is a filename.
# File descriptor "M" is redirect to file "N."

Example: To redirect stdout to filename
To redirect stderr to errorlog

Another format is
# "M" is a file descriptor, which defaults to 1, if not set.
# "N" is another file descriptor.

Example: To redirect both stderr and stdout to the same file
1>somefile 2>&1

More about I/O redirection here.

No comments: