假设我向函数传递了2个参数。如何将邮件重定向到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
答案 0 :(得分:3)
只需将>&2
添加到产生输出的语句中即可:
echo "Too many operands." >&2
,如果您也希望将其附加到名为err.txt
的文件中,则:
echo "Too many operands." | tee -a 'err.txt' >&2
FWIW我将使用一个case语句而不是嵌套的if
编写您的代码(并整理几件事):
#!/bin/env bash
case $# in
0 ) dir='.' ;;
1 ) dir="$1" ;;
* ) printf 'Too many operands: %d\n' "$#" | tee -a 'err.txt' >&2
exit 1 ;;
esac