You are not logged in.

#1 2019-07-30 07:20:32

brontosaurusrex
Middle Office
Registered: 2015-09-29
Posts: 2,746

Bash way to try N times and else exit ?

In reality this could be a method to wait for until something is ready, but only wait for some time, I came up with this monster example

#!/bin/bash

# tries

# player 1
num1="$(( RANDOM % 6 + 1 ))"
echo "num1=${num1}"

# player 2
n="6" # retries

# action
for i in $(seq 1 $n); do 

    num2="$(( RANDOM % 6 + 1 ))"
    echo "num2=${num2} $i"
    (( num2 == num1 )) && break
    # sleep 1
    
done 

# results
if (( i == n )) && (( num2 != num1 )); then

    echo "Not guessed in $n tries"
    exit 1

else

    echo "Bravo!"
    
fi

Shorter, nicer, more readable version?

Last edited by brontosaurusrex (2019-07-30 11:01:31)

Offline

Board footer

Powered by FluxBB