# Prime Number Calculation using shell scripting

``````#!/bin/bash
echo -e "Enter Number : \c"
while [ \$n -gt 2 ]
do
for((i=2; i<=\$n/2; i++))
do
ans=\$(( n%i ))
if [ \$ans -eq 0 ]
then
echo "\$n is not a prime number."
exit 0
fi
done
done
echo "\$n is a prime number."
``````

The new code:

``````#!/bin/bash
echo -e "Enter Number : \c"
for((i=2; i<=\$n/2; i++))
do
ans=\$(( n%i ))
if [ \$ans -eq 0 ]
then
echo "\$n is not a prime number."
exit 0
fi
done
echo "\$n is a prime number."
``````

The outer while loop is infinite:

``````while [ \$n -gt 2 ]
``````

A working version:

``````#!/bin/bash
echo -e "Enter Number : \c"
for((i=2; i<=\$n/2; i++))
do
ans=\$(( n%i ))
if [ \$ans -eq 0 ]
then
echo "\$n is not a prime number."
exit 0
fi
done
echo "\$n is a prime number."
``````
• But last line is not executing I tried with 13. Mar 21, 2020 at 14:39
• @AnkitKumar Works for me. Mar 21, 2020 at 14:43
• The cursor keeps on blinking and does not show the number is prime . I'm using ubuntu 18 Mar 21, 2020 at 14:51
• @AnkitKumar show the new code in https://pastebin.com/. Mar 21, 2020 at 15:01
• @guillermochamorro no, please don't. The new code should be added to the question.
– terdon
Mar 21, 2020 at 15:19
``````#! /bin/bash

read -p "Enter number: " n

d=2
r=1
while [[ \$d -lt \$n && \$r -ne 0 ]]
do
r=`expr \$n % \$d`

d=`expr \$d + 1`
done

if [[ \$r -eq 0 ]]
then
echo "\$n is not a prime number"
else
echo "\$n is a prime number"
fi
``````
``````#!/bin/bash

i=2
while ((\$i<\$j))
do
f=((j%i))
if [ \$f -eq 0] && [ \$j -ne \$i ]
then
# echo "is a not prime number"
i=\$i+\$j
elif [ \$f -ne 0 ]
then
((i++))
else [ \$j -ne \$i ]
then
echo "is a prime number"
fi
done
``````