Thursday, November 24, 2005

stderr

I've run programs before that huff and puff and produce ... an error message. If the output is going into some archive, or is input into another program, I usually don't find out about the error until too late, and I think, "Gee. I wish it had beeped or something."

In well-designed programs, errors are announced through a separate channel from normal output.

On Linux, default output goes to "standard output" (stdout), while errors go to "standard error" (stderr). These are two separate channels. Both go to the screen by default, but you can redirect them separately.

Try this. First, snarf-and-barf this script into the file hello:

#!/bin/sh

echo hello, world
ls A_NONEXISTENT_FILE
Run hello and you'll see this:
hello, world
ls: A_NONEXISTENT_FILE: No such file or directory
Next, use the command-line-editing keys to redirect the output into a file. What happens?
hello > OUT
You can capture the errors with the construction "2>"
hello 2> ERR
You can redirect both separately.
hello > OUT 2> ERR
Try this and think about what happens.
hello > OUT 2> OUT
Try redirecting either channel to the bit-bucket, /dev/null. Then make up experiments of your own.

Oh, Happy Thanksgiving!

0 Comments:

Post a Comment

<< Home