1

Related to SO.

fizzy.sh:

#!/usr/bin/env sh

div3() {
    expr $1 % 3 = 0
}

div5() {
    expr $1 % 5 = 0
}

fizzy() {
    if [ $(div3 $1) ] && [ $(div5 $1) ]; then
        expr "FizzBuzz"
    elif [ $(div3 $1) ]; then
        expr "Fizz"
    elif [ $(div5 $1) ]; then
        expr "Buzz"
    else
        expr "$1"
    fi
}

echo $(fizzy 1)
echo $(fizzy 2)
echo $(fizzy 3)

Example:

$ ./fizzy.sh
FizzBuzz
FizzBuzz
FizzBuzz
Community
  • 1
  • 1
mcandre
  • 22,868
  • 20
  • 88
  • 147

3 Answers3

1

expr $1 % 3 = 0 yields 1 or 0, depending on whether the result of $1 % 3 is zero or not, but if treats 0 as true, not false.

sh-3.2$ if [ 0 ]; then echo ok; fi
ok

So you'd need to compare the output of your function against 1. Something like this:

#!/usr/bin/env sh

div3() {
    expr $1 % 3 = 0
}

div5() {
    expr $1 % 5 = 0
}

fizzy() {
    if [ $(div3 $1) -eq 1 ] && [ $(div5 $1) -eq 1 ]; then
        expr "FizzBuzz"
    elif [ $(div3 $1) -eq 1 ]; then
        expr "Fizz"
    elif [ $(div5 $1) -eq 1 ]; then
        expr "Buzz"
    else
        expr "$1"
    fi
}

for (( i = 1; i <= 15; i++ ))
do
    echo $(fizzy $i)
done
Simon Whitaker
  • 20,506
  • 4
  • 62
  • 79
  • The `if [ 0 ]; ...` test isn't doing what you think it is. You get the same result with `if [ 1 ]` or `if [ cow ]` or any non-empty string. This will demonstrate what you want: `if $(exit 0); then echo Y; else echo N; fi` and test again with 1 intead of 0 – glenn jackman Nov 04 '11 at 18:38
1

Without the need for div3 or div5 functions.

fizzbuzz() { # eg: fizzbuzz 10
   ((($1%15==0))&& echo FizzBuzz)||
   ((($1%5==0))&& echo Buzz)||
   ((($1%3==0))&& echo Fizz)||
   echo $1;
}

Or you could do it all at once

fizzbuzz() { # eg: fizzbuzz
for i in {1..100};
do
   ((($i%15==0))&& echo FizzBuzz)||
   ((($i%5==0))&& echo Buzz)||
   ((($i%3==0))&& echo Fizz)||
   echo $i;
done;
}
coelmay
  • 51
  • 4
0

If your shell is bash, you don't need to call out to expr:

div3() { (( $1 % 3 == 0 )); }
div5() { (( $1 % 5 == 0 )); }

fizzbuzz() {
  if div3 $1 && div5 $1; then
    echo FizzBuzz
  elif div3 $1; then
    echo Fizz
  elif div5 $1; then
    echo Buzz
  else
    echo
  fi
}

for ((n=10; n<=15; n++)); do
  printf "%d\t%s\n" $n $(fizzbuzz $n)
done
glenn jackman
  • 238,783
  • 38
  • 220
  • 352