echo输出到stderr

echo输出到stderr

On the unix command line, each command can print to stdout (standard output) or stderr (standard error). By convention, error messages go to stderr, and normal messages go to stdout. You usually connect stdout to the stdin (standard input) of another process. Having a long pipe of commands and this stderr/stdout convention means that the error messages from one command don't go polluting the input to the next command. It also means that you can see the error messages of the commands, since stderr is shown on your terminal (if they were printed to stdout, then you would not see the error messages, since they would be sent to the input of another command).

When writing your own little scripts, it's a good idea to print your error messages to stderr. The usual way to print in a bash script is to use the echo shell builtin command. You can "echo" to stderr like this:

echo "Your error message here" >&2

This is a normal echo (which goes to stdout), however the >&2 (which is shorthand for 1>&2), means 'mix the stdout to the stderr'. 1 is stdout, and 2 is stderr here.

你可能感兴趣的:(shell)