'how to print prime numbers using for loop in shell script

I want to print prime numbers using for loop in shell script. Please provide some suggestions.

actually I could able to print odd numbers from range of 1 to 100, but now I am unable to print prime numbers. Provide some script to print prime numbers

# cat prime.sh
#!/bin/bash
for ((i=1; i<=100; i++))

do

      output=$(( $i % 2))

      if [ $output -ne 0 ]

      then
      echo "We got odd numbers: $i"
      fi
done


Solution 1:[1]

The below code returns the list of prime numbers within a specified range.

the below command returns the prime numbers between 10 to 30

./filename.sh 10 30

#!/bin/bash
# Check if a number is prime

# function to return whether prime or not
check_prime() {
    current_number=$1
    flag=0
    i=2

    while test $i -le `expr $current_number / 2`
    do
        if test `expr $current_number % $i` -eq 0
        then
            flag=1
        fi
        i=`expr $i + 1`
    done

    if test $flag -eq 0
        then echo $current_number
    fi
}

# Assign From and to number
from_number=$1
to_number=$2

for (( number=$from_number; number<=$to_number; number++ ))
do
    check_prime $number
done

Solution 2:[2]

This code will Print all prime numbers upto given number & also print count of it hope it helps !!

#!/bin/bash

echo "enter a number upto which you want the prime numbers"
read num
count=0
for (( n=2; n<=$num; n++ ))
do

t=1

if [ $n -lt 2 ]
then echo "Please give other  numbers than 0 and 1"
else
#echo $n
for (( i=2; i<$n; i++ ))
do
        #echo $n
        if (($n%i==0))
        then
        #echo "$n is not prime number"
        t=0
        break;
        fi
done
#echo $t
        if [ $t == 1 ]
        then
        echo "$n is a prime number"
        count=`expr $count + 1`
        fi
fi
done
echo "Total prime numbers upto $num are $count "

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sidharthan Kamaraj
Solution 2