0

Im trying a code in bash to generate prime nos as follows:

#!/bin/bash


echo "Enter till where u wish to generate"
read num
echo "Generating prime numbers from 2 to $num"

flag="prime"

for i in {2..$num}
do

for j in {2..$((${num}-1))}
 do

 [ $((${i}%${j})) -eq 0 ] && flag="nprime" || flag="prime"
 break
 done

 [ "$flag" == "prime" ] && echo "$i"

done

Upon execution, it throws an error because the for loop takes the sequence mentioned in the curly braces as it is not as a sequence. Could you guide me as to where am i going wrong ?

abhishek nair
  • 324
  • 1
  • 6
  • 18

2 Answers2

2

man bash in my version says:

A sequence expression takes the form {x..y[..incr]}, where x and y are either integers or single characters, and incr, an optional increment, is an integer.

You can't use variables in ranges. Try seq instead:

for i in $(seq 2 $num) ; do

Note that incr for seq goes between x and y.

choroba
  • 231,213
  • 25
  • 204
  • 289
2

Use:

for ((i=2; i<=$num; i++))
Cyrus
  • 84,225
  • 14
  • 89
  • 153