简体   繁体   English

如何将输出重定向到 STDERR?

[英]How to redirect output to STDERR?

Suppose that I passed in 2 parameters to my function.假设我将 2 个参数传递给我的函数。 How can I redirect a message to stderr?如何将消息重定向到 stderr?

#!/bin/bash
if [ $# = 0 ]; then
    dir="."
elif [ $# = 1 ]; then
    dir=$1
elif [ $# -ge 2 ]; then
    echo "Too many operands." 2>> err.txt //???
    exit 1
fi

Just add >&2 to the statement producing the output:只需将>&2添加到生成输出的语句中:

echo "Too many operands." >&2

and if you want it to be appended to a file named err.txt too:如果您也希望将其附加到名为err.txt的文件中:

echo "Too many operands." | tee -a 'err.txt' >&2

FWIW I'd write your code using a case statement instead of nested if s (and tidy up a couple of things): FWIW 我会使用 case 语句而不是嵌套if s(并整理一些东西)来编写您的代码:

#!/bin/env bash
case $# in
    0 ) dir='.' ;;
    1 ) dir="$1" ;;
    * ) printf 'Too many operands: %d\n' "$#" | tee -a 'err.txt' >&2
        exit 1 ;;
esac

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM