linux - 不能在算术表达式中使用乘法

标签 linux bash shell ubuntu

#!/bin/bash
if [ $# -lt 3 ] ;then
        echo "USAGE : calculate.sh VAR1 OPERATOR VAR2"
exit 1
fi
VAR1=$1
OP=$2
VAR2=$3
if [ $OP = '+' ];then
        echo "$VAR1+$VAR2=$[$VAR1+$VAR2]"
        exit 0
elif [ $OP = '-' ];then
        echo "$VAR1-$VAR2=$[$VAR1-$VAR2]"
        exit 0
elif [ $OP = '*' ];then
        echo "$VAR1*$VAR2=$[$VAR1*$VAR2]"
        exit 0;
else
        echo "$VAR1/$VAR2=$[$VAR1/$VAR2]"
fi

以上是calculate.sh的内容。

如果我使用 +-/,我会得到正确的答案,但是当我使用 *,报错:

 kdyzm@kdyzm:~/scripts$ ./calculate.sh 2 + 3 
 2+3=5
 kdyzm@kdyzm:~/scripts$ ./calculate.sh 2 - 3 
 2-3=-1
 kdyzm@kdyzm:~/scripts$ ./calculate.sh 2 * 3
 ./calculate.sh: line 21: 2/command.sh: syntax error: invalid arithmetic operator (error token is ".sh")
 kdyzm@kdyzm:~/scripts$ ./calculate.sh 2 / 3 
 2/3=0
 kdyzm@kdyzm:~/scripts$

我该如何解决这个问题?

最佳答案

当你想传递一个*时,你必须引用参数:

./calculate.sh 2 \* 3 

关于linux - 不能在算术表达式中使用乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35153561/

相关文章:

linux - 用 bash 脚本解析 `ls -l` 的结果

c - 当用户放弃 root 权限时打开文件时权限被拒绝

linux - 如何删除vi文件中的列?

shell - 逐行读取并写入另一个文件shell脚本

linux - 如何使用 mutt 在程序完成时向我发送通知

python - 将 C++ 包装到 Python - 其中部分代码是没有源代码的共享库

linux - 修改可执行文件的链接路径

bash - 如何更改 Bash 中二级变量的值?

linux - 带有 cron 作业的 Shell 脚本在未运行的情况下启动程序?

linux - 强制为 shell 脚本中的每个命令运行 `tee`?