[英]How to redirect output to STDERR?
假設我將 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
只需將>&2
添加到生成輸出的語句中:
echo "Too many operands." >&2
如果您也希望將其附加到名為err.txt
的文件中:
echo "Too many operands." | tee -a 'err.txt' >&2
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.