# 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