Thursday, March 17, 2005

Bash - Stdout and Stderr redirection to a file

There is a difference between giving:
command >file1 2>file1
and
command > file1 2>&1

In the former case, the two redirections maintain two different file handles and hence the data might not be what we expect it to be.
Try the following in a script:
#!/bin/bash

exec >foo1 2>foo1
echo hello >&1
echo boss >&2

In the latter case however, the two redirections share the same handle. Hence this is preferred for most purposes.
Try the following in a script:
#!/bin/bash

exec >foo2 2>&1
echo hello >&1
echo boss >&2

Now try cat of foo1 and foo2 to see the differences.

Hop this helps.
Rgds,
Karthick S.

0 comments: