for 

Indexed for loop
"Borrowed" from the c-shell.


for (( initial condition[s]; test condition[s]; modifier ))
do
  action list
done


For indexed for loop, bash allows the use of braces {}
  to encapsulate the action body instead of the do and done
  keywords.


for (( initial condition[s]; limiting condition[s]; modifiers ))
{
  action list
}



  • for - keyword.
  • (( )) - open and closed double parentheses encapsulate the parameters for initialization, loop continuation condition, and adjustments.
  • initial condition[s] - list statement[s] that usually initialize variables.
  • limiting condition[s] - conditional test statement evaluated to continue.
  • modifier - arithmetic expression performed after each pass through action block.
      Run after test condition and for-loop action block executed.
         #The final echo will print out 2
         for (( num=1; num<2; num++ )); {   echo $num; }  
         echo $num
      
      Usually some adjustment applied to modify value of variable being tested. Available mathematical operators
        = : set value *= : multiply by specified value i*=2 /= : divide by specified value j/=3 %= : mod with specified value, place remainder in variable i%=2 += : increment by specified value i+=2 ++ : increment by 1 -= : decrement by specified value -- : decrement by 1 <<= : bit shift left by value >>= : bit shift right by &= : bit and ^= : bit xor |= : bit or
      Action[s] consist of mathematical statements. Does not run until after 1st pass through loop body. Multiple comma delimited adjustments can be listed. Modifier section can be left blank. for (( sum=0; sum < 1000; )) do read -p "Number : " val sum=$( expr $sum + $val ) done Arithmetic adjustments don't have to be applied to variable being tested.
      j=20
      
      for (( i=1; i <= 10; i++,j-- ))
      do 
        echo $i $j
      done
      
      

      #!/bin/bash
      
      # Get a random number from 0-99
      target=$( expr $RANDOM % 100 )
      # get first guess
      read -p "Guess : " guess
      
      # set guess count to 1
      # test guess against target
      #  if mis-guess then test for too high or low
      # increment guess count if missed.
      for (( i = 1; "$guess" != "$target"; i++ ))
      do
        if [ "$guess" -gt "$target" ]
        then
           echo "too high"
        else
           echo "too low"
        fi
      
        read -p "Guess : " guess
      done
      
      # show target and number of guesses.
      echo "$target in $i guesses"