我正在做一个简单的计算器,可以选择是否继续。但是当我尝试乘法运算时,我在控制台中出错:
calculator.sh: line 17: [: too many arguments
calculator.sh: line 22: [: too many arguments
calculator.sh: line 27: [: too many arguments
calculator.sh: line 32: [: too many arguments
这基本上意味着我的所有操作都有此错误,但当我使用它们时,情况并非如此,它们会正常运行。 我在堆栈溢出中搜索相似之处,但示例不同。我用斜线逃脱了*,但我认为它与角色#34; *"进行比较时会出错。为了到达if语句的主体。 这是代码:
#!/bin/bash
choice="Y"
while [ $choice == "Y" ]
do
echo -n "Enter first value:"
read firstvar
echo -n "Enter second value:"
read secondvar
echo -n "Enter last value:"
read compvar
echo -n "Enter operation:"
read ops
counter=0
result=0
while [ $result != $compvar ]
do
if [ $ops == "+" ]
then result=$((firstvar+secondvar))
echo "Do you want to continue ? Y/N"
read choice
break
elif [ $ops == "-" ]
then result=$((firstvar-secondvar))
echo "Do you want to continue ? Y/N"
read choice
break
elif [ $ops == "*" ]
then result=$((firstvar\*secondvar))
echo "Do you want to continue ? Y/N"
read choice
break
elif [ $ops == "/" ]
then result=$((firstvar/secondvar))
echo "Do you want to continue ? Y/N"
read choice
break
else
echo "Input valid operation !!!"
echo "Do you want to continue ? Y/N"
read choice
break
fi
counter=$((counter+1))
done
done
答案 0 :(得分:2)
问题可能不是因为脚本中的"*"
,而是因为$ops
变量中的星号。
您应该对变量进行双引号以避免将globbing应用于它们;像这样重写你的测试:
elif [ "$ops" = "*" ]
这是一个非常有用的resource for checking your shell scripts。
答案 1 :(得分:0)
首先,请查看Charles Duffy的评论WRT“==”vs“=”进行字符串测试。 将$ ops的出现更改为“$ {ops}”。 删除result = $((firstvar * secondvar))中的转义。 我冒昧地重新编写了脚本。 希望这会有所帮助。
#!/bin/bash
choice="Y"
while [ $choice = "Y" ]
do
echo -n "Enter first value:"
read firstvar
echo -n "Enter second value:"
read secondvar
echo -n "Enter last value:"
read compvar
echo -n "Enter operation:"
read ops
counter=0
result=0
while [ $result != $compvar ]
do
if [ "${ops}" = "+" ]; then
result=$((firstvar+secondvar))
echo "Do you want to continue ? Y/N"
read choice
break
elif [ "${ops}" = "-" ]; then
result=$((firstvar-secondvar))
echo "Do you want to continue ? Y/N"
read choice
break
elif [ "${ops}" = "*" ]; then
result=$((firstvar*secondvar))
echo "Do you want to continue ? Y/N"
read choice
break
elif [ "${ops}" = "/" ]; then
result=$((firstvar/secondvar))
echo "Do you want to continue ? Y/N"
read choice
break
else
echo "Input valid operation !!!"
echo "Do you want to continue ? Y/N"
read choice
break
fi
counter=$((counter+1))
done
done