Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to exit or retry based on long running command result

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading