I have a simple script:
is_prime () {
local factors
factors=( $( factor "$1" | cut -d ':' -f 2 ) )
[ ${#factors} -le 1 ]
}
starting () {
for i in $(seq 10 99); do
if is_prime "$i" ; then echo "$i" ; fi
done
}
starting
If I run it with /bin/zsh, it prints all the primes between 10 and 99, as I would expect. If I run it with /bin/bash, however, it does the exact opposite: it prints all non-prime values in that range! I understand zshs behaviour, but why does bash do what it does? Is the behaviour of test different in some relevant way?
for ((i=10; i<99; i++))instead offor i in $(seq ...); this keeps evaluation internal to the shell rather than launching a nonstandardized external tool. (I've actually seen someone build an implementation ofseqthat spelled out numbers just to mess with people --one,two, etc; there's no POSIX standard for it, so it's perfectly legal for it to do weird things, or simply not be there at all).cut:factor_str=$(factor "$1"); factor_str=${factor_str#*:}; read -A factors <<<"$factor_str"(in zsh), orread -a factors <<<"$factor_str"(in bash). Frankly, they're different enough shells that it assuming that things will work between them isn't a great habit to be in.