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

相关内容