0% found this document useful (0 votes)
5 views2 pages

Main Bash

The document is a Bash script that checks if input numbers are prime. It prompts the user to enter numbers, validates them, and identifies which are prime, displaying the results. If no valid prime numbers are found, it notifies the user accordingly.

Uploaded by

himaeel734
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Main Bash

The document is a Bash script that checks if input numbers are prime. It prompts the user to enter numbers, validates them, and identifies which are prime, displaying the results. If no valid prime numbers are found, it notifies the user accordingly.

Uploaded by

himaeel734
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

# Online Bash Shell.

# Code, Compile, Run and Debug Bash script online.


# Write your code in this editor and press "Run" button to execute it.

#!/bin/bash

# Function to check if a number is prime


is_prime() {
local num=$1

# Return false if number is less than or equal to 1


if [[ $num -le 1 ]];
then
printf "false\n"
return
fi

# Check for divisibility up to square root of the number


local divisor=2
while [[ $((divisor * divisor)) -le $num ]];
do
if [[ $((num % divisor)) -eq 0 ]];
then
printf "false\n"
return
fi
((divisor++))
done

# Number is prime
printf "true\n"
}

# Prompt user to input numbers


echo -n "Enter numbers separated by spaces: "
read -r user_input

# Split input into an array


IFS=' ' read -ra input_numbers <<< "$user_input"

# Check if input is empty


if [[ $ {#input_numbers[@]} -eq 0 ]];
then
echo "Error: No numbers provided"
exit 1
fi

# Array to store prime numbers


declare -a primes_found

# Process each number in the input


for number in "${input_numbers[@]}";
do
# Validate that the input is a positive integer
if [[ ! $number =~ ^[0-9]+$ ]];
then
echo "Warning: '$number' is not a valid integer, skipping"
continue
fi

# Check if number is prime and store if true


if [[ $(is_prime "$number") == "true" ]];
then
primes_found+=("$number")
fi
done

# Display the results


if [[ $ {#primes_found[@]} -eq 0 ]];
then
echo "No prime numbers found in the input"
else
echo "Prime numbers: ${primes_found[*]}"
echo "Total prime numbers: ${#primes_found[@]}"
fi

You might also like