在 shell 脚本中与 expr 相乘

新手上路,请多包涵

我正在制作一个基本的计算器来进行加减乘除。

加法有效,但乘法无效。当我尝试乘法时,我得到“您没有正确运行程序”响应:

 $ ./calculator 4 + 5
9
$ ./calculator 4 * 5
You did not run the program correctly
Example: calculator 4 + 5

我在谷歌上四处搜索,在那里我找到了 \\* 代码,但仍然不起作用。有人可以为我提供解决方案或解释吗?

这是我的代码

#!/bin/bash

if [ $# != 3 ]; then
  echo You did not run the program correctly
  echo Example: calculator 4 + 5
  exit 1
fi

if [ $2 = "+" ]; then
  ANSWER=`expr $1 + $3`
 echo $ANSWER
fi

if [ $2 = "*" ]; then
  ANSWER=`expr $1 \\* $3`
  echo $ANSWER
fi

exit 0

原文由 Alex Wolfe 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 522
1 个回答

你的代码有很多问题。这是一个修复。 * 表示“当前目录下的所有文件”。要改为表示文字星号/乘法字符,您必须对其进行转义:

 ./calculator 3 \* 2

或者

./calculator 3 "*" 2

您还必须双引号 "$2" ,否则 * 将再次开始表示“所有文件”:

 #!/bin/bash
#Calculator
#if [ `id -u` != 0 ]; then
#  echo "Only root may run this program." ; exit 1
#fi
if [ $# != 3 ]; then
  echo "You did not run the program correctly"
  echo "Example:  calculator 4 + 5"
  exit 1
fi
# Now do the math (note quotes)
if [ "$2" = "+" ]; then echo `expr $1 + $3`
elif [ "$2" = "-" ]; then echo `expr $1 - $3`
elif [ "$2" = "*" ]; then echo `expr $1 \* $3`
elif [ "$2" = "/" ]; then echo `expr $1 / $3`
fi
exit 0

原文由 hongo 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题