Linux 错误calc bash脚本 #/bin/bash 如果[$2==“+”];然后 回声$1+3 | bc elif[$2==“-”];然后 回音公元前1-3美元 elif[$2==“/”];然后 echo$1/$3 | bc-l elif[${2:-0}==“\*”];然后 回音:公元前1\*$3 fi [ali@localhost桌面]$/q1.sh 5\*2 ./q1.sh:第4行:[:参数太多 ./q1.sh:第6行:[:参数太多 ./q1.sh:第8行:[:参数太多 ./q1.sh:第10行:[:参数太多

Linux 错误calc bash脚本 #/bin/bash 如果[$2==“+”];然后 回声$1+3 | bc elif[$2==“-”];然后 回音公元前1-3美元 elif[$2==“/”];然后 echo$1/$3 | bc-l elif[${2:-0}==“\*”];然后 回音:公元前1\*$3 fi [ali@localhost桌面]$/q1.sh 5\*2 ./q1.sh:第4行:[:参数太多 ./q1.sh:第6行:[:参数太多 ./q1.sh:第8行:[:参数太多 ./q1.sh:第10行:[:参数太多,linux,bash,shell,Linux,Bash,Shell,下面的脚本可以: #!/bin/bash if [ "$2" = "+" ] # == won't work with old test ie [], #use [[ ]] if you wish to use == then echo "$1 + $3" | bc elif [ "$2" = "-" ]; then echo "$1 - $3" | bc elif [ "$2" = "/" ]; then if [

下面的脚本可以:

   #!/bin/bash
    if [ "$2" = "+" ] # == won't work with old test ie [],
    #use [[ ]]  if you wish to use ==
    then
     echo "$1 + $3" | bc
    elif [ "$2" = "-" ]; then
     echo "$1 - $3" | bc
    elif [ "$2" = "/" ]; then
      if [ "$3" -ne 0 ]
      then
        echo "scale=3;$1 / $3" | bc -l # scale gives the precision of the results
      else
        echo "Division by zero not possible"
      fi
    elif [ "$2" = '*' ]; then
       # You need to escape or quote the asterisk in the command line
       # when calling the script like ./script 3 \* 4
       echo "$1 * $3" | bc
    fi 2>/dev/null # For suppressing the errors when using '\*' as $2
样本运行

$ ./38464438.sh 4 + 5
9
$ ./38464438.sh 4 - 5
-1
$ ./38464438.sh 4 / 5
.800
$ ./38464438.sh 4 \* 5
20
除非有很好的理由不引用参数扩展。当
$2
*
(如您的示例中所示)时,它将进行路径名扩展。
*
扩展到当前工作目录中的每个文件,这将为
[
命令生成太多的参数

if [ "$2" = "+" ]; then
(另外,不要将
==
[
一起使用;请使用正确的相等运算符
=


额外建议:您的脚本将
*
作为参数接收,而不是
\*
,因此您的最终比较应该是

elif  [ "$2" = "*" ]; then
输出:

10
35.63705

只是一个想法..方括号是test命令的快捷方式--因此变量本身中的一些特殊字符可能会将字符串分解为“多个参数”…请阅读。这将有助于你以一种有助于我们帮助你的方式写下你的问题。对于反对者,我忘记引用一些我已经纠正过的变量。这是反对者投票的唯一原因吗?
q1 5 \* 2
q1 'scale=5; sqrt( 9^2 + 10^2 + 33^2 )'
10
35.63705