Danny Danny - 1 month ago 22
Bash Question

Shell for loop, stopping at declaration

I'm trying to write a for loop that goes from 1 to 10, then calculates ( 1 through 10 mod 5) + 2. After that I want to display it like this (1 to 10 mod 5) + 2 = answer. However i'm getting an error at the beginning of the loop which is a syntax error.

for (( i = 0; i <= 10; i++)); do
calculate=(i % 5) + 2
echo ("("i "% 5) + 2" calculate)
done

Answer

Try these changes:

calculate=$(( i % 5 + 2 ))         
  # $(( ... )) is the shell's way to do arithmetic
echo "($i % 5) + 2 = " $calculate  
  # $x is a way to refer to the value of variable x 
  # (also inside a double-quoted string)

The for loop header is actually OK.