I read this blog posting on a trivial programming test at two in the morning and I got worried: was I an actual programmer? Thus I decided to implement FizzBuzz in bash 3:

for i in {1..100}
  ([ $(($i % 15)) -eq 0 ] && echo FizzBuzz ) || \
  ([ $(($i % 3)) -eq 0 ] && echo Fizz ) || \
  ([ $(($i % 5)) -eq 0 ] && echo Buzz ) || \
  echo $i

A few thoughts:

  1. Note the use of the new bash 3 builtin iterator {1..100} to generate the list instead of using a counter variable, seq, or jot.
  2. Note also the use of bash builtin arithmetic evaluation instead of bc or expr.
  3. I wrote this in the one line style with conditional operators instead of branching. For some reason I am more comfortable in that style.
  4. Is there a way to make the return value of a math operation be the mathematical result? I couldn't think of one offhand. That leads to the awkward [ x -eq 0 ] construct. I suspect that could be replaced with a combination of expr and eval.

I'd like to hear if anyone can write this in a more compact and/or elegant fashion in bash 3. However, I'm not really interested in going the obfuscated code route - what's the most compact way you can write this script that is still readable and elegant?



Our Founder
ToolboxClick to hide/show
RecentChanges Click to hide/show