错误计算bash脚本

时间:2016-07-19 17:00:55

标签: linux bash shell

#!/bin/bash


if [ $2 == "+" ]; then
    echo $1 + $3 | bc
elif [ $2 == "-" ]; then
 echo $1 -$3 | bc
 elif [ $2 == "/" ]; then
 echo $1 / $3 | bc -l
 elif  [ ${2: -0} == "\*" ]; then
  echo $1 \* $3 | bc
fi





[ali@localhost Desktop]$ ./q1.sh 5 \* 2
./q1.sh: line 4: [: too many arguments
./q1.sh: line 6: [: too many arguments
./q1.sh: line 8: [: too many arguments
./q1.sh: line 10: [: too many arguments

3 个答案:

答案 0 :(得分:1)

#!/bin/bash
bc <<< "$@"

示例:

q1 5 \* 2
q1 'scale=5; sqrt( 9^2 + 10^2 + 33^2 )'

输出:

10
35.63705

答案 1 :(得分:0)

以下脚本可以:

   #!/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 :(得分:0)

始终引用您的参数扩展,除非您有充分的理由不这样做。当$2*时(如您的示例所示),它会经历路径名扩展。 *扩展到当前工作目录中的每个文件,这会为[命令生成太多参数。

if [ "$2" = "+" ]; then

(另外,请勿将==[一起使用;请使用正确的等号运算符=。)

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

elif  [ "$2" = "*" ]; then