Bourne shell: Force STDOUT to STDERR
sh, shell
Solution
shell redirects are evaluated one-at-a-time, left-to-right. So when you have:
# ls foo bar >&2 2>/tmp/test
That FIRST redirects stdout to stderr (whatever it was initially -- probably the terminal) and THEN redirects stderr to /tmp/test. So stdout will be left pointing at whatever stderr was originally pointed at and not at the file. You want
# ls foo bar 2>/tmp/test >&2
redirect stderr to the file FIRST, and THEN redirect stdout to the same place.
Problem
I am creating a Subversion post-commit hook. I need to force the output of one command to STDERR, so that the post-commit hook will marshal the message back to the client. How can I force STDOUT to STDERR? In this simplified example, the file `foo` exists, but `bar` does not. ``` # touch foo # ls foo bar ls: bar: No such file or directory foo ``` I want to send STDOUT to STDERR. I assumed that I could do this with `>&2`, but it doesn't seem to be working. I was expecting following example to redirect STDOUT to STDERR, and that `/tmp/test` would would contain the output and error for the command. But instead, it appears that STDOUT is never redirected to STDERR, and thus `/tmp/test` only contains the error from the command. ``` # ls foo bar >&2 2>/tmp/test foo # cat /tmp/test ls: bar: No such file or directory ``` What am I missing? I have tried the above example on CentOS, Ubuntu, FreeBSD and MacOSX.