Bash 计算参数

Bash counting Arguments

我在计算我在 shell 脚本中输入的参数时遇到问题。我的脚本假设通过在我的代码末尾使用和 Else 语句来回显 "You have entered too many arguments"。如果我输入超过 3 个,我什么也得不到。我是否遗漏了一些简单的东西,或者我应该将其更改为案例陈述。我是 shell 脚本的新手,因此非常感谢任何帮助。

#!/bin/bash
clear

Today=$(date +"%m-%d-%y")
echo -en '\n'
echo "To find out more about this calculator please refer to the calc.readme file."
echo -en '\n'
echo "You entered $*"
echo -en '\n'
if [ "$#" -eq "3" ]; then
if   [ "" == "+" ]; then
    answer=`expr  + `
    echo "You entered the correct amount of arguments"
    echo -en '\n'
    echo "Your total is: "`expr  + `
    echo "[$Today]: $@ = $answer"  >> calc.history
elif [ "" == "-" ]; then
    answer=`expr  - `
    echo "You entered the correct amount of arguments"
    echo -en '\n'
    echo "Your total is: "`expr  - `
    echo "[$Today]: $@ = $answer" >> calc.history
 elif [ "" == "*" ]; then
    answer=`expr  \* `
    echo "You entered the correct amount of arguments"
    echo -en '\n'
    echo "Your total is: "`expr  \* `
    echo "[$Today]: $@ = $answer" >> calc.history
 elif [ "" == "/" ]; then
    asnwer=`expr  / `
    echo "You entered the correct amount of arguments"
    echo -en '\n'
    echo "Your total is: "`expr  / `
    echo "[$Today]: $@ = $answer" >> calc.history
 else
    echo -en '\n'
    echo "You entered too many arguments."
  fi
  fi

您的 if 语句嵌套错误。您写道:

if <test on number of arguments>
  if <values>
  else
    <wrong number of arguments>
  fi
fi

虽然你应该写:

if <test on number of arguments>
  if <values>
  fi
else
  <wrong number of arguments>
fi

您的 else 语句与错误的 if 语句关联,但您可以用单个 case 语句替换大 if-elif 链。

#!/bin/bash
clear

today=$(date +"%m-%d-%y")
echo
echo "To find out more about this calculator please refer to the calc.readme file."
echo
echo "You entered $*"
echo

if [ "$#" -eq "3" ]; then
  echo "You entered the correct amount of arguments"
  case  in
    [+-*/])
      echo
      answer=$((    ))
      echo "Your total is $answer"
      echo "[$today]: $@ = $answer" >> calc.history
      ;;
    *) echo "Unrecognized operator "
       ;;
  esac
else
  echo
  echo "You entered too many arguments."
fi