echo that outputs to stderr
Is there a standard Bash tool that acts like echo but outputs to stderr rather than stdout?
 I know I can do echo foo 1>&2 but it's kinda ugly and, I suspect, error prone (eg more likely to get edited wrong when things change).  
This question is old, but you could do this, which facilitates reading:
>&2 echo "error"
 The operator >&2 literally means redirect the address of file descriptor 1 ( stdout ) to the address of file descriptor 2 ( stderr ) for that command1.  Depending on how deeply you want to understand it, read this: http://wiki.bash-hackers.org/howto/redirection_tutorial  
To avoid interaction with other redirections use subshell
(>&2 echo "error")
 1 >&2 copies file descriptor #2 to file descriptor #1.  Therefore, after this redirection is performed, both file descriptors will refer to the same file: the one file descriptor #2 was originally referring to.  
You could define a function:
echoerr() { echo "$@" 1>&2; }
echoerr hello world
This would be faster than a script and have no dependencies.
Camilo Martin's bash specific suggestion uses a "here string" and will print anything you pass to it, including arguments (-n) that echo would normally swallow:
echoerr() { cat <<< "$@" 1>&2; }
Glenn Jackman's solution also avoids the argument swallowing problem:
echoerr() { printf "%sn" "$*" >&2; }
 Since 1 is the standard output, you do not have to explicitly name it in front of an output redirection like > but instead can simply type:  
echo This message goes to stderr >&2
 Since you seem to be worried that 1>&2 will be difficult for you to reliably type, the elimination of the redundant 1 might be a slight encouragement to you!  
上一篇: 什么是特殊的美元符号shell变量?
下一篇: 将输出回送给stderr
