Home > Net >  How to exit or retry based on long running command result
How to exit or retry based on long running command result

Time:07-06

I am trying to monitor the output of long_running_command function(can't make changes to this), If the output contains result='good' then print WOW and return. However, until the long_running_command did not return result='good' keep trying until MAX_TRY is reached. So far its all good. However, if the command already returned result='failed' then there is no point of retrying, how can I error out(print NAY) without retrying ?

Below is sample program(Minimum working problem statement):

#!/bin/bash

MAX_TRY=5


#Simulating a fake long running command that may return good or failed randomly with a small delay
long_running_command()
{

    wait_time=$(shuf -i 1-5 -n 1)
    sleep "$wait_time"

    if [ "$path" -eq 1 ];then
        echo "result='good'"
    elif [ "$path" -eq 0 ];then
        echo "result='failed'"
    else
        echo "This path should never hit"
    fi

}



# Some external conditions cannot be controlled by me, faking it
#0 means fail
#1 means pass
path=$(shuf -i 0-1 -n 1)



check_result() {
    while [ $MAX_TRY -le 10 ];do
    if long_running_command |grep -qE 'result.*good' ;then
        echo "$(date): WOW"
        return 0 
    fi
        echo "$(date): Retrying...so far the output does not have good in it or perhaps its failed already"
    MAX_TRY=$((MAX_TRY   1))
         
    done
    echo "$(date): NAY"
}

check_result

TLDR, I need to exit from the retry loop if the command has returned failed or good. Later, print `WOW or NAY based on the results.

CodePudding user response:

Save the output in a variable. Then you can test whether it contains result='good' or result='failed'. If neither, you retry.

check_result() {
    while [ $MAX_TRY -le 10 ]
    do
        output=$(long_running_command | grep -E "result='(good|failed)'")
        case "$output" in
            *good*) 
                # Return success immediately
                echo "$(date): WOW"
                return 0
                ;;
            *failed*)
                # No point in retrying
                break
                ;;
        esac
        MAX_TRY=$((MAX_TRY   1))
    done
    echo "$(date): NAY"
    return 1
}
  • Related