2023-03-22 10:00:09

输出到stderr的echo

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

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


当前回答

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

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

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

其他回答

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

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

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

James Roth和Glenn Jackman建议的组合解决方案

添加ANSI颜色代码以红色显示错误消息:

echoerr() { printf "\e[31;1m%s\e[0m\n" "$*" >&2; }

# if somehow \e is not working on your terminal, use \u001b instead
# echoerr() { printf "\u001b[31;1m%s\u001b[0m\n" "$*" >&2; }

echoerr "This error message should be RED"

我最近偶然发现的另一个选项是:

    {
        echo "First error line"
        echo "Second error line"
        echo "Third error line"
    } >&2

这只使用Bash内置程序,同时使多行错误输出不易出错(因为您不必记住在每行中添加&>2)。

您可以定义函数:

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