2

I just found the following FizzBuzz example on Hacker News and it uses a piece of syntax I'm finding it difficult to search for

for num in {1..100} ; do
  out=""
  (( $num % 3 == 0 )) && out="Fizz"
  (( $num % 5 == 0 )) && out="${out}Buzz"
  echo ${out:-$num}
done

The bit I don't understand is how the variable usage works in the echo line. Though I can obviously see that it becomes $out if not empty, else $num

Peter R
  • 414
  • 2
  • 10
  • It is a default `:-`, if out is nothing print the number. Second piece of code on here http://tldp.org/LDP/abs/html/parameter-substitution.html –  Jan 21 '15 at 10:19

1 Answers1

4
for num in {1..100} ; do 

Loop from 1 to 100.Set num to each integer on the way

out=""

Set out to nothing

(( $num % 3 == 0 )) && out="Fizz"

If the number is divisible by 3 set out to Fizz

  (( $num % 5 == 0 )) && out="${out}Buzz"

If the number is divisible by 5 set out to whatever is contained in out then Buzz.

  echo ${out:-$num}

Uses parameter substitution to check that out contains something, if it does not, then use num instead. Echos result of the substitution.

done

Resources

http://tldp.org/LDP/abs/html/parameter-substitution.html - parameter substitution

http://tldp.org/LDP/abs/html/ops.html - let command ((...))

http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-7.html - loops

Tensibai
  • 15,557
  • 1
  • 37
  • 57
  • @PeterR I rejected the edit as although it contains some information you may not have wanted, it may be useful for others. It isn't too long for the information you did want to be easily locatable. –  Jan 21 '15 at 10:49
  • It is at the very end of the post, and there are plenty of easily searchable posts that cover the other material. I am very thankful you took the time to help me and you don't have to edit your post, but I also don't have to set best answer - though I would very much like to be able to – Peter R Jan 22 '15 at 17:48