Thursday, March 17, 2005

Bash - How to redirect stdout and stderr to the same 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.
I will discuss how this happens in a different post.
Post a Comment