
我有一個從某處複製的有效的 global_exit ,它用於兩個命令退出。將“echo”重命名為“ech”以強制失敗,使我能夠測試所有排列工作 - 它們在這裡執行:
echo "$USER $(date +%F)" |& tee info.log
info_exit=${PIPESTATUS[0]}
echo "$USER $(date +%F)" |& tee list.log
list_exit=${PIPESTATUS[0]}
global_exit=$(( info_exit > list_exit ? info_exit : list_exit ))
if [ ${global_exit} = "0" ]; then
echo ">> SUCCESS <<"
elif [ ${global_exit} = "1" ]; then
echo ">> WARNINGS <<"
else
echo ">> FAILED <<"
fi
exit
我如何將其擴展到三個 RC?我還沒有找到有關如何使用此功能的規則。我只是猜測使用下面的內容,但它不適用於同一測試的所有排列(將一個 echo 逐一重命名為 ech 以強制失敗):
echo "$USER $(date +%F)" |& tee info.log
info_exit=${PIPESTATUS[0]}
echo "$USER $(date +%F)" |& tee list.log
list_exit=${PIPESTATUS[0]}
echo "$USER $(date +%F)" |& tee check.log
check_exit=${PIPESTATUS[0]}
global_exit=$((( info_exit > list_exit > check_exit ? info_exit : list_exit > check_exit )))
if [ ${global_exit} = "0" ]; then
echo ">> SUCCESS <<"
elif [ ${global_exit} = "1" ]; then
echo ">> WARNINGS <<"
else
echo ">> FAILED <<"
fi
exit
謝謝 :)
答案1
如果我的意圖是正確的,並且您希望繼續使用所編寫的程式碼,請更改以下內容:
global_exit=$((( info_exit > list_exit > check_exit ? info_exit : list_exit > check_exit )))
對此:
global_exit=$((( info_exit > list_exit > check_exit ? info_exit : list_exit > check_exit ? list_exit : check_exit )))
正如你所知道的,如果 info_exit 最大,它就可以正常工作。如果不是,則根據 list_exit > check_exit 是否將 global_exit 設為 0 或 1。新增附加條件後,它將被設定為 list_exit 或 check_exit 中的較大者。
答案2
一起檢查 0、1 和所有其他返回碼的一種可能性是組合返回碼:
echo "$USER $(date +%F)" |& tee info.log
exit_code=$((exit_code | PIPESTATUS[0]))
echo "$USER $(date +%F)" |& tee list.log
exit_code=$((exit_code | PIPESTATUS[0]))
echo "$USER $(date +%F)" |& tee check.log
exit_code=$((exit_code | PIPESTATUS[0]))
if (( 0 == exit_code )); then
echo ">> SUCCESS <<"
elif (( 1 == exit_code )); then
echo ">> WARNING <<"
else
echo ">> FAILED <<"
fi
使用這種方法,您無法區分退出代碼,並且可能會出現多個回傳代碼,但對於一般的 OK/Not OK 回傳代碼來說應該足夠了。
答案3
你可以使用一個函數並檢查全部狀態碼PIPESTATUS
並保存最高值。
#!/bin/bash
max_exit=0
set_max_exit() {
for i in "${PIPESTATUS[@]}"; do
[ "$i" -gt "$max_exit" ] && max_exit=$i
done
}
echo | grep x # exit 1
set_max_exit
ech # exit 127
set_max_exit
ls adfds # exit 2
set_max_exit
if [ "$max_exit" -eq 0 ]; then
echo ">> SUCCESS <<"
elif [ "$max_exit" -eq 1 ]; then
echo ">> WARNING <<" >&2
else
echo ">> FAILED <<" >&2
fi
exit "$max_exit"
輸出:
$ ./script.sh
./script.sh: line 14: ech: command not found
ls: cannot access 'adfds': No such file or directory
>> FAILED <<
$ echo $?
127