无论布尔值如何,Bash始终打印相同的值

时间:2011-11-03 22:14:15

标签: bash if-statement boolean conditional-statements

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)

示例:

$ ./fizzy.sh
FizzBuzz
FizzBuzz
FizzBuzz

3 个答案:

答案 0 :(得分:1)

expr $1 % 3 = 0产生1或0,具体取决于$1 % 3的结果是否为零,但if将0视为真,而不是假。

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

所以你需要将你的函数输出与1进行比较。这样的事情:

#!/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

答案 1 :(得分:1)

无需div3或div5函数。

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

或者你可以一次完成所有这些

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;
}

答案 2 :(得分:0)

如果您的shell是bash,则无需呼叫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