• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer navigation

The Geek Diary

  • OS
    • Linux
    • CentOS/RHEL
    • VCS
  • Interview Questions
  • Database
    • MariaDB
  • DevOps
    • Docker
    • Shell Scripting
  • Big Data
    • Hadoop
    • Cloudera
    • Hortonworks HDP

Shell/Bash Script to Find Prime Numbers in Linux

by admin

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<=n;))
do
  for((j=i-1;j>=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).

find prime number using shell script

Filed Under: DevOps, Linux, Shell Scripting

Some more articles you might also be interested in …

  1. wall: command not found
  2. lftp: command not found
  3. quota Command Examples in Linux
  4. calligraflow: Calligra’s flowchart and diagram application
  5. mkinitrd: command not found
  6. in-toto-record Command Examples
  7. cvs: Concurrent Versions System, a revision control system
  8. startkde: command not found
  9. hostname Command Examples in Linux
  10. mailq Command Examples in Linux

You May Also Like

Primary Sidebar

Recent Posts

  • Vanilla OS 2 Released: A New Era for Linux Enthusiasts
  • mk Command Examples
  • mixxx Command Examples
  • mix Command Examples

© 2025 · The Geek Diary

  • Archives
  • Contact Us
  • Copyright