Linux特殊shell意味着问题

时间:2013-12-14 08:40:49

标签: linux bash shell

如何使此代码有效,以便将“*”和mod“%”相乘不会收到错误消息?我的想法是因为它们对shell有特殊意义。我该怎么把它拿走?

#!/bin/bash

echo "Enter Number Operator Number"
echo "[Operators +, -, /, *, %]"
echo -n " --->   "

read num1 op num2

case $op in

  +) printf "$num1 + $num2 = %d\n" `expr $num1 $op $num2`

     ;;

  -) printf "$num1 - $num2 = %d\n" `expr $num1 $op $num2`

     ;;
  /) printf "$num1 / $num2 = %d\n" `expr $num1 $op $num2`

     ;;

  \*) printf "$num1 * $num2 = %d\n" `expr $num1 $op $num2`

     ;;
  %) printf "$num1 % $num2 = %d\n" `expr $num1 $op $num2`

     ;;

  *) echo "Bad Operator: $op choose [+, -, *, /, %]"

     ;;

esac

3 个答案:

答案 0 :(得分:3)

感谢使用$(())算术扩展,您的整个脚本可以简化为:

#!/bin/bash

echo "Enter Number Operator Number"
echo "[Operators +, -, /, *, %]"
echo -n " --->   "

read num1 op num2

case "$op" in
    +|-|\*|/|%) echo "$num1 $op $num2 =" $((num1 $op num2)) ;;
    *) echo "Bad Operator: $op choose [+, -, *, /, %]" ;;
esac

您可以在man bash算术扩展部分阅读更多相关信息。

答案 1 :(得分:1)

除非您特意希望进行单词拆分和通配,否则您应该始终引用您的变量。

case "$op" in
  +) printf "$num1 + $num2 = %d\n" `expr "$num1" "$op" "$num2"`
     ;;
  -) printf "$num1 - $num2 = %d\n" `expr "$num1" "$op" "$num2"`
     ;;
  /) printf "$num1 / $num2 = %d\n" `expr "$num1" "$op" "$num2"`
     ;;
  \*) printf "$num1 * $num2 = %d\n" `expr "$num1" "$op" "$num2"`
     ;;
  %) printf "$num1 % $num2 = %d\n" `expr "$num1" "$op" "$num2"`
     ;;
  *) echo "Bad Operator: $op choose [+, -, *, /, %]"
     ;;
esac

答案 2 :(得分:1)

最简单的方法是使用(( ))运算符。

您的行应如下所示:

printf "$num1 + $num2 = %d\n" $(( expr $num1 $op $num2 ))

您不会遇到不带引号的变量问题。 :)