Created
June 12, 2024 13:59
-
-
Save BruXy/b835ef31017cb02b2b3c79c247b35317 to your computer and use it in GitHub Desktop.
Repeat iteration of bash for-cycle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
DATA=(10 20 30 40 50 60 70 80 90 100) | |
DATA_LEN=$[ ${#DATA[*]} - 1 ] | |
TIME_OUT=22 | |
execution=0 # Count total number of cycles | |
result=1 # initialized as failed | |
start_time=$(date +%s) | |
function dummy_task() { | |
# Just sleep and return random results | |
sleep 1.5 | |
return $[RANDOM%2] # 0 OK, 1 fail | |
} | |
for i in $(seq 0 $DATA_LEN) | |
do | |
while [ $result -ne 0 ] ; do | |
# Time out check | |
current_time=$(date +%s) | |
if [ $TIME_OUT -le $[current_time - start_time] ] ; | |
then | |
printf "Process took more than %d secs, exiting...\n" $TIME_OUT | |
exit 1 | |
fi | |
: $[execution++] | |
# Main task | |
dummy_task | |
result=$? | |
printf "Loop $i Item ${DATA[i]} : $result (exec $execution)" | |
if [ $result -eq 0 ] ; then | |
printf " OK\n" | |
result=1 | |
break | |
else | |
printf " FAIL, restarting\n" | |
continue | |
fi | |
done | |
done | |
printf "It took $execution cycles to finish processing.\n" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
DATA=(10 20 30 40 50 60 70 80 90 100) | |
DATA_LEN=$[ ${#DATA[*]} - 1 ] | |
TIME_OUT=22 | |
execution=0 # Count total number of cycles | |
result=1 # initialized as failed | |
function wait_kill() { | |
local ppid=$1 | |
local time_out=$2 | |
sleep $time_out | |
kill -s TERM $ppid | |
printf "Process took more than %d secs, exiting...\n" $TIME_OUT | |
exit | |
} | |
function dummy_task() { | |
# Just sleep and return random results | |
sleep 1.0 | |
return $[RANDOM%2] # 0 OK, 1 fail | |
} | |
wait_kill $$ $TIME_OUT & | |
wait_pid=$! | |
for i in $(seq 0 $DATA_LEN) | |
do | |
while [ $result -ne 0 ] ; do | |
: $[execution++] | |
# Main task | |
dummy_task | |
result=$? | |
printf "Loop $i Item ${DATA[i]} : $result (exec $execution)" | |
if [ $result -eq 0 ] ; then | |
printf " OK\n" | |
result=1 | |
break | |
else | |
printf " FAIL, restarting\n" | |
continue | |
fi | |
done | |
done | |
kill -s TERM $wait_pid | |
printf "It took $execution cycles to finish processing.\n" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment