whileループのアイデア

whileループのアイデア
n=0
while [ $n -le 10 ]
do
if sapcontrol -nr "$sid" -function GetSystemInstanceList | grep 'GREEN|YELLOW' 
else
echo "SAP System successfully stopped!"
break
fi  
done

状態が黄色と緑の場合はスキップし、灰色に変わるのを待ってループを切断します。 3分後にグレーでない場合は、エラーレポートが表示されます。

どうすればいいのアイデアはありますか?ありがとうございます!

ベストアンサー1

以下のスクリプトには必要なものがすべてあると思います。

#!/usr/bin/env bash

# set defaults for used variables.
# variables could be set this way:
#   var=foo var2=bar ./loopscript.sh
max_runtime_sec=${max_runtime_sec:-180}
recheck_time_sec=${recheck_time_sec:-5}


while true; do
        # use pre-defined VAL or use default (output of sapcontrol)
        # debugging: set VAL as commandlin arg and comment out the next line
        VAL=$(sapcontrol -nr "$sid" -function GetSystemInstanceList | grep 'GREEN|YELLOW')
        # switch-case with case-ignore Value of last command
        case ${VAL,,} in
                *green*|*yellow*)
                        if [[ $SECONDS > $max_runtime_sec ]]; then
                                echo "Error: max runtime of $max_runtime_sec seconds hit."
                                echo "       Now breaking out of loop."
                                break
                        fi
                        # reduce system load and retry
                        sleep $recheck_time_sec
                        continue        # do next loop iteration
                        ;;
                *gray*)
                        echo "Info: found VAL $VAL"
                        echo "       Now breaking out of loop."
                        break
                        ;;
                *)
                        echo "Error: no valid VAL found. "
                        echo "       stopping script now."
                        exit 1
                        ;;
        esac
done
echo "SAP System successfully stopped!"

さまざまな値で出力テスト:

$ time max_runtime_sec=4 VAL=green ./loop.sh
Error: max runtime of 4 seconds hit at Tue Feb 18 16:46:13 CET 2020. Script start at Tue Feb 18 16:46:08 CET 2020
       Now breaking out of loop.
SAP System successfully stopped!

real    0m5,019s
user    0m0,013s
sys     0m0,004s

$ time max_runtime_sec=4 VAL=yellow ./loop.sh
Error: max runtime of 4 seconds hit at Tue Feb 18 16:46:25 CET 2020. Script start at Tue Feb 18 16:46:20 CET 2020
       Now breaking out of loop.
SAP System successfully stopped!

real    0m5,016s
user    0m0,012s
sys     0m0,004s

$ time max_runtime_sec=4 VAL=grey ./loop.sh
Info: found VAL grey
       Now breaking out of loop.
SAP System successfully stopped!

real    0m0,005s
user    0m0,005s
sys     0m0,001s

$ time max_runtime_sec=4 VAL=foo ./loop.sh
Error: no valid VAL found.
       stopping script now.

real    0m0,007s
user    0m0,002s
sys     0m0,006s

おすすめ記事