4 ms·
Your bash example could be a little cleaner. Since 0 is truthy in bash and [ `expr something` ] is, for most purposes, (( )). for i in {1..100}; do
by Spivak 8y ago
Your bash example could be a little cleaner. Since 0 is truthy in bash and [ `expr something` ] is, for most purposes, (( )).
for i in {1..100}; do
if (( $i % 3 && $i % 5 )); then
echo FizzBuzz
elif (( $i % 3 )); then
echo Fizz
elif (( $i % 5 )); then
echo Buzz
else
echo $i
fi
done
Bash also has a decently powerful matching statement so you can do something similar to the rust example.
for i in {1..100}; do
case "$(( $i % 3 ))$(( $i % 5 ))" in
00)
echo FizzBuzz
;;
0*)
echo Fizz
;;
*0)
echo Buzz
;;
*)
echo $i
;;
esac
done
- esoterae 8y agoicydk, $ is redundant on alpha variable names within $(( ... ) HNY! (:
- tyingq 8y ago#/bin/bash for n in {1..100} ; do f="" ((n % 3)) || f="Fizz" ((n % 5)) || f="${f}Buzz" echo ${f:-$n} done
- gshubert17 8y agoBash exit code 0 is truthy, but that's not how the if statement works: if ((0)); then echo 0=true; else echo 0=false; fi if ((1)); then echo 1=true; else echo 1=false; fi # output 0=false 1=true To work as expected, the if statements should be rewritten as if ((i % 3 == 0 && i % 5 == 0)); then echo FizzBuzz and so on.