You are not logged in.

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

brontosaurusrex
Middle Office
Registered: 2015-09-29
Posts: 1,799
Website

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

#2 2019-07-30 10:35:34

earlybird
ほやほや
Registered: 2015-12-16
Posts: 711
Website

Re: Bash way to try N times and else exit ?

Bash has surprisingly complete support for C-style for-loops:

#!/bin/bash

action () {
  echo a
  return 1
}

die () {
  echo 'I am dead now'
  exit 1
}

#######################################################################
# What matters
#######################################################################

for ((
  tries=3, status=1, attempt=0;
  status==1 && (attempt<tries);
  attempt++
)); do
  action; status=$?
done

(( status == 0 )) || die

#######################################################################

echo 'I have survived'

exit 0

Offline

#3 2019-07-30 11:02:51

brontosaurusrex
Middle Office
Registered: 2015-09-29
Posts: 1,799
Website

Re: Bash way to try N times and else exit ?

@earlybird; That for loop is just awesome.

Offline

#4 2019-07-30 16:50:32

twoion
ほやほや
Registered: 2015-08-10
Posts: 2,464

Re: Bash way to try N times and else exit ?

On a second thought:

action; status=$?

should probably be, if you need a generic statement

action; status=$(( !($? == 0) ))

because commands can have an exit status that is neither 0 nor 1!


A silent kite against the blue, blue sky

Offline

Board footer

Powered by FluxBB