Monday, January 31, 2022

[SOLVED] Retry logic for below piece of code in Unix shell script

Issue

We have one unix job which always get failed due to following error

unable to execute os command

and just after retrying in second or third run it successfully executed.

So now I want retry logic up to 3 times for the below piece of code, please give example for below code.

If execution is successful in first run then it should come out of loop else it should continue retrying till 3 times. Then after it should come out of loop and process remaining code.

sqlplus -s / <<EOF
        set serveroutput on size 999999
        set feed off
        set term off
        spool ../logs/$PROGRAM.log3
        execute $PROGRAM;
EOF
 

Solution

You could do something like this

iteration=0 
limit=3 
seconds_in_wait=10 

while [[ $iteration -le $limit ]];
do

sqlplus -s / <<EOF
        whenever sqlerror exit 99;
        set serveroutput on size 999999
        set feed off
        set term off
        spool ../logs/$PROGRAM.log3
        execute $PROGRAM;
EOF

if [[ $? -eq 99 ]];
then 
    if [[ $iteration -eq $limit ]];
    then 
        echo "Maximum times allowed - Error"
        exit 2;
    else
        iteration = $(expr $iteration + 1)
        sleep $seconds_in_wait 
    fi 
else
    iteration=$(expr $limit + 1)
fi 

done
  • You define a limit of iterations, in my example 3
  • If the process fails, you wait for a number of seconds and try again
  • If the process fails and you reach the limit, then you exit with error
  • If it does not fail, you exit the loop


Answered By - Roberto Hernandez
Answer Checked By - Marie Seifert (WPSolving Admin)