2023-03-22 10:00:09

输出到stderr的echo

是否有一个标准的Bash工具,其行为类似于echo,但输出到stderr而不是stdout?

我知道我可以做echo foo 1>&2,但它有点难看,而且,我怀疑,容易出错(例如,当事情发生变化时,更容易编辑错误)。


当前回答

如果您不介意将消息也记录到syslog,那么not_so_丑陋的方法是:

logger -s $msg

-s选项表示:“将消息输出到标准错误和系统日志。”

其他回答

这是一个简单的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

您可以定义函数:

echoerr() { echo "$@" 1>&2; }
echoerr hello world

这将比脚本更快,并且没有依赖关系。

卡米洛·马丁的bash特定建议使用“here字符串”,并将打印传递给它的任何内容,包括echo通常会接受的参数(-n):

echoerr() { cat <<< "$@" 1>&2; }

格伦·杰克曼的解决方案也避免了吞论点的问题:

echoerr() { printf "%s\n" "$*" >&2; }

如果您不介意将消息也记录到syslog,那么not_so_丑陋的方法是:

logger -s $msg

-s选项表示:“将消息输出到标准错误和系统日志。”

read是一个shell内置命令,可打印到stderr,可以像echo一样使用,而无需执行重定向技巧:

read -t 0.1 -p "This will be sent to stderr"

-t 0.1是一个超时,它禁用读取的主要功能,将一行stdin存储到变量中。

另一种选择

echo foo >>/dev/stderr