#!/bin/bash
# Function to check if a number is prime
is_prime() {
local num=$1
# 0 and 1 are not prime numbers
if [ $num -lt 2 ]; then
return 1
fi
# Loop to check divisibility by numbers up to the square root of the number
for (( i = 2; i * i <= num; i++ )); do
if [ $((num % i)) -eq 0 ]; then
return 1
fi
done
return 0
}
# Check if the script is executed with an argument
if [ $# -eq 0 ]; then
echo "Usage: ./prime_check.sh <number>"
exit 1
fi
# Check if the input is a non-negative integer
if ! [[ $1 =~ ^[0-9]+$ ]]; then
echo "Error: Please enter a non-negative integer."
exit 1
fi
# Call the function to check if the number is prime
is_prime $1
if [ $? -eq 0 ]; then
echo "$1 is a prime number."
else
echo "$1 is not a prime number."
fi
./prime_check.sh 3
Write, Run & Share Bash code online using OneCompiler's Online Bash Shell for free. It's one of the robust, feature-rich Bash shell available over online and getting started with the OneCompiler's Bash Shell is simple and pretty fast. The editor shows sample boilerplate code when you choose language as Bash. OneCompiler also has reference scripts, where you can look for the sample scripts and start coding.
Bash (Bourne Again Shell) is a shell program written by Brian Fox and is an upgraded version of Bourne Shell program 'sh'.
name="Foo"
echo $name
echo "$name"
echo "${name}"
if [ conditional-expression ]
then
statements
fi
if [ conditional-expression ]
then
statements
else
statements
fi
if [ conditional-expression ]
then
statements
elif [ conditional-expression ]
then
statements
else
statements
fi