Conditions in 'for' Loop

Hey guys, I've been learning shell for a few weeks now & come across an issue in one of my for loops :

However I wish to add a condition (maybe if loop is best ??) when, if the variable value $line is > 24 go back to the start of my 'for' loop thus skipping my application based commands and incrementing i by one.

I have tired using the above, but fail to get it working properly.

Thank You

I am not quite sure if you want to test the value someone enters, ie. some number or, if you want 24 times some input? Or both?

Maybe something like this?

$> while read I; do if (( $I < 24 )); then echo ok; else echo err; fi; done
22
ok
25
err
28
err

---------- Post updated at 04:13 PM ---------- Previous update was at 03:57 PM ----------

After reading it again I assume I understood it now:

#!/bin/bash

COUNTER=0
MAX=5

while read INPUT; do
   if (( $INPUT > 24 )); then
      if (( $COUNTER < $MAX)); then
         COUNTER=$(($COUNTER + 1))
         echo "Increasing COUNTER to $COUNTER."
      else
         echo "Reached the maximum tries was $COUNTER, aborting."
         break
      fi
   else
      echo "Doing nothing"
   fi
done

exit 0

Output:

1
Doing nothing
2
Doing nothing
3
Doing nothing
24
Doing nothing
25
Increasing COUNTER to 1.
26
Increasing COUNTER to 2.
27
Increasing COUNTER to 3.
28
Increasing COUNTER to 4.
10
Doing nothing
30
Increasing COUNTER to 5.
12
Doing nothing
31
Reached the maximum tries was 5, aborting.
1 Like

If you are validating input to make sure you get an integer below 25 (i.e. <=24) then you could consider this in korn shell:-

#!/bin/ksh
typeset -i i=100          # Set as integer

until [ $i -ge 0 -a $i -le 24 ]
do
  read input?"Please enter a value zero to 24:- "
  i=$input
  if [ "$i" != "$input" ]
  then
     i=100
  fi
done

# Whatever comes next

Does that help? The use of variable input is just to have something to compare to to check that we have an integer input. If it's not, then the assignment to i will fail, leaving i as zero and as that is a permitted value in the loop, it would normally be accepted. I code around that by setting it 100 if the input and the integer being really tested don't match. The if statement has to use string function tests else you get syntax errors.

I hope that this is useful

Robin
Liverpool/Blackburn

This is looks like it will do the trick.... however I am getting these errors :

When I use the below command the scrip appears to hang :wall:

Thank You

EDIT:
Zaxxon: Found out the issue is to do with reading my 'INPUT' file....It appears it is not reading the the value in my text file. Before I was using 'read -r' to read each indivdual line for each time the the statement loops around. However I am having trouble implementing this into this loop.