I am writing a bash script to find all of the prime numbers less than a given integer.
Here is the code:
#!/bin/bash
BADARGS=65
if [ -z $1 ]
then
echo "Usage:`basename $0` cannot have a null parameter."
exit $BADARGS
elif [ $1 -lt 2 ]
then
echo "Usage:`basename $0` should have the value 2 or more as the parameter."
exit $BADARGS
fi
TRUE=0
FALSE=
Primes(){
checkPrime=( $(factor $1) ) # this puts factors into array
if [ -z "${checkPrime[2]}" ] # third element is null
then
return $TRUE
else
return $FALSE
fi
}
printf "2 "
let "n = 3"
while [ $n -le $1 ]
do
if Primes $n
then
printf "$n "
fi
let "n += 2"
done
printf "\n"
# END
I am using MacOS and when I execute the script I receive this error message:
Jessicas-MacBook-Pro:Documents jessicalott$ ./primes.sh 10
2 ./primes.sh: line 16: factor: command not found
3 ./primes.sh: line 16: factor: command not found
5 ./primes.sh: line 16: factor: command not found
7 ./primes.sh: line 16: factor: command not found
9
I literally starting writing in bash this morning so any help would be appreciated. I think it might have something to do with the fact that I am not using Linux, but I hope that is not the case.
factor
is not a standard Unix command. Linux has it. OS X does not.
As mentioned in a comment, factor is part of GNU coreutils. You can install coreutils with Homebrew:
brew install coreutils
After that factor
can be replaced with /usr/local/bin/gfactor
in the script.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With