是否有一个标准的Bash工具,其行为类似于echo,但输出到stderr而不是stdout?
我知道我可以做echo foo 1>&2,但它有点难看,而且,我怀疑,容易出错(例如,当事情发生变化时,更容易编辑错误)。
是否有一个标准的Bash工具,其行为类似于echo,但输出到stderr而不是stdout?
我知道我可以做echo foo 1>&2,但它有点难看,而且,我怀疑,容易出错(例如,当事情发生变化时,更容易编辑错误)。
当前回答
这是一个简单的STDERR函数,它将管道输入重定向到STDERR。
#!/bin/bash
# *************************************************************
# This function redirect the pipe input to STDERR.
#
# @param stream
# @return string
#
function STDERR () {
cat - 1>&2
}
# remove the directory /bubu
if rm /bubu 2>/dev/null; then
echo "Bubu is gone."
else
echo "Has anyone seen Bubu?" | STDERR
fi
# run the bubu.sh and redirect you output
tux@earth:~$ ./bubu.sh >/tmp/bubu.log 2>/tmp/bubu.err
其他回答
你可以这样做,这有助于阅读:
>&2 echo "error"
>&2将文件描述符#2复制到文件描述符#1。因此,执行此重定向后,两个文件描述符将引用同一个文件:最初引用的是一个文件描述符#2。有关更多信息,请参阅Bash Hackers Illustrated redirection Tutorial。
您可以定义函数:
echoerr() { echo "$@" 1>&2; }
echoerr hello world
这将比脚本更快,并且没有依赖关系。
卡米洛·马丁的bash特定建议使用“here字符串”,并将打印传递给它的任何内容,包括echo通常会接受的参数(-n):
echoerr() { cat <<< "$@" 1>&2; }
格伦·杰克曼的解决方案也避免了吞论点的问题:
echoerr() { printf "%s\n" "$*" >&2; }
这是一个简单的STDERR函数,它将管道输入重定向到STDERR。
#!/bin/bash
# *************************************************************
# This function redirect the pipe input to STDERR.
#
# @param stream
# @return string
#
function STDERR () {
cat - 1>&2
}
# remove the directory /bubu
if rm /bubu 2>/dev/null; then
echo "Bubu is gone."
else
echo "Has anyone seen Bubu?" | STDERR
fi
# run the bubu.sh and redirect you output
tux@earth:~$ ./bubu.sh >/tmp/bubu.log 2>/tmp/bubu.err
另一种选择
echo foo >>/dev/stderr
我最近偶然发现的另一个选项是:
{
echo "First error line"
echo "Second error line"
echo "Third error line"
} >&2
这只使用Bash内置程序,同时使多行错误输出不易出错(因为您不必记住在每行中添加&>2)。