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存储到变量中。

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

这里有一个函数用于检查最后一个命令的退出状态,显示错误并终止脚本。

or_exit() {
    local exit_status=$?
    local message=$*

    if [ "$exit_status" -gt 0 ]
    then
        echo "$(date '+%F %T') [$(basename "$0" .sh)] [ERROR] $message" >&2
        exit "$exit_status"
    fi
}

用法:

gzip "$data_dir"
    or_exit "Cannot gzip $data_dir"

rm -rf "$junk"
    or_exit Cannot remove $junk folder

该函数打印脚本名称和日期,以便在从crontab调用脚本并记录错误时有用。

59 23 * * * /my/backup.sh 2>> /my/error.log

您可以定义函数:

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

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

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

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

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

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

由于1是标准输出,因此不必在输出重定向前显式命名它,如>。相反,您可以简单地键入:

echo This message goes to stderr >&2

由于您似乎担心1>&2对您来说很难可靠地打字,因此删除多余的1可能会对您有一点鼓励!