Write a shell script to check if the number entered at the command line is prime or not.
Write a shell script to check if the number entered at the command line is prime or not.
CODE:
#!/bin/bash
# Function to check if a number is prime
is_prime() {
num=$1
if [ $num -lt 2 ]; then
echo "$num is not prime."
exit 1
fi
for ((i=2; i*i<=$num; i++)); do
if [ $((num % i)) -eq 0 ]; then
echo "$num is not prime."
exit 1
fi
done
echo "$num is prime."
}
# Check if a number is provided as a command-line argument
if [ $# -eq 0 ]; then
echo "Usage: $0 <number>"
exit 1
fi
# Get the number from the command line
number=$1
# Call the is_prime function with the provided number
is_prime $number
Save this script in a file, for example, check_prime.sh
, and make it executable using the following command:
chmod +x check_prime.sh
You can then run the script by providing a number as a command-line argument:
./check_prime.sh 17
This will output:
"17 is prime."
Post a Comment