我在计算我在shell脚本中输入的参数时遇到了问题。我的脚本假设通过在代码末尾使用和Else语句来回显“你输入了太多参数”。如果我输入超过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 [ "$2" == "+" ]; then
answer=`expr $1 + $3`
echo "You entered the correct amount of arguments"
echo -en '\n'
echo "Your total is: "`expr $1 + $3`
echo "[$Today]: $@ = $answer" >> calc.history
elif [ "$2" == "-" ]; then
answer=`expr $1 - $3`
echo "You entered the correct amount of arguments"
echo -en '\n'
echo "Your total is: "`expr $1 - $3`
echo "[$Today]: $@ = $answer" >> calc.history
elif [ "$2" == "*" ]; then
answer=`expr $1 \* $3`
echo "You entered the correct amount of arguments"
echo -en '\n'
echo "Your total is: "`expr $1 \* $3`
echo "[$Today]: $@ = $answer" >> calc.history
elif [ "$2" == "/" ]; then
asnwer=`expr $1 / $3`
echo "You entered the correct amount of arguments"
echo -en '\n'
echo "Your total is: "`expr $1 / $3`
echo "[$Today]: $@ = $answer" >> calc.history
else
echo -en '\n'
echo "You entered too many arguments."
fi
fi
答案 0 :(得分:3)
您的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
答案 1 :(得分:3)
您的else
语句与错误的if
语句相关联,但您可以使用单个if-elif
语句替换大case
个链。
#!/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 $2 in
[+-*/])
echo
answer=$(( $1 $2 $3 ))
echo "Your total is $answer"
echo "[$today]: $@ = $answer" >> calc.history
;;
*) echo "Unrecognized operator $2"
;;
esac
else
echo
echo "You entered too many arguments."
fi