Shell/Bash Script to Find Prime Numbers in Linux

A prime number is a whole number that has exactly 2 different factors, 1 and itself. A number that is not a prime number will be called composite. Except 1 each natural number that is divisible by only 1 and itself is called a prime number. For example: 2,3,5,7,11,13,17,19,23,29… etc.

  • There are total 25 prime number upto 100 and 46 prime numbers upto 200.
  • 2 is the only prime number and the smallest prime number, rest all prime numbers are odd.
  • 1 is neither prime not composite number.

Bash Script to Find Prime number is a given Range of Numbers

1. Configure the script as shown below in /tmp/prime_num.sh file:

#!/bin/bash

prime_1=0
echo "enter the range"
read n
echo " Prime number between 1 to $n is:"
echo "1"  
echo "2"
for((i=3;i=2;))
  do
    if [  `expr $i % $j` -ne 0 ] ; then
      prime_1=1
    else
      prime_1=0
      break
    fi
    j=`expr $j - 1`
  done
  if [ $prime_1 -eq 1 ] ; then
    echo $i
  fi
  i=`expr $i + 1`
done

2. Assign executible permissions to the file before running it:

$ chmod +x /tmp/prime_num.sh

3. Run the script as shown below and provide a range (for example 50 to find prime numbers between 0 to 50).

Related Post