我正在使用while命令编写一个shell程序,以防止被零除,并在用户键入99时退出程序。每次运行它时,我得到第二个数字的输入错误不给我答案。以下是我对此问题的尝试:
#!/bin/bash
firstNum=0
secondNum=0
answer=0
while true firstNum != 99, secondNum != 99 do
read -p "Enter first number" firstNum
read -p "Enter second number" secondNum
echo "first num $firstNum"
echo "second Num $secondNum"
if ["$secondNum" = "0"]
then
exit 1
else
echo "first number / second Number = $((firstNum/secondNum))"
echo "Answer = $answer"
fi
do
exit
done
以下是我收到的错误消息
./example.sh: 10: ./example.sh: [2: not found
非常感谢任何帮助。 感谢
答案 0 :(得分:2)
看起来像是一些错别字。
替换它:
if ["$secondNum" = "0"] then
exit 1
then
echo "1st number / 2nd number = $((firstNum/secondNum))"
echo "Answer = $answer"
fi
用这个:
if [ "$secondNum" = "0" ]
then
exit 1
else
echo "1st number / 2nd number = $((firstNum/secondNum))"
echo "Answer = $answer"
fi
巴什很挑剔。确保then
位于下一行,与if
不在同一行,您的第3行也有then
而不是else
。
答案 1 :(得分:2)
您的代码可以简化
while true; do
read -p "Enter first number: " firstNum
[[ "$firstNum" -eq 99 ]] && break
read -p "Enter second number: " secondNum
case "$secondNum" in
99) break ;;
0) echo "div by zero, try again"; continue ;;
esac
echo "first number / second Number = $(bc -l <<< "$firstNum/$secondNum")"
done
我呼吁bc
获取浮点运算。使用shell,你只能限制为整数。
<<<
是&#34; here-string&#34;,一个传递给bc&#39; sdin的字符串
答案 2 :(得分:1)
你的代码看起来对我很好,但是我稍微改变了POSIX shell测试以测试小于99而不是99本身的值。并且我删除了脚本底部附近的一个流浪do
。 Bash也有[[]]
样式测试语法,你可能希望在某些时候切换到它。
#!/bin/bash
firstNum=0
secondNum=0
answer=0
while [ "$firstNum" -lt 99 -a "$secondNum" -lt 99 ]
do
read -p "Enter first number " firstNum
read -p "Enter second number " secondNum
printf "first num $firstNum\n"
printf "second Num $secondNum\n"
if [ "$secondNum" = 0 ]
then
printf "$secondNum was a zero, exiting!\n"
exit 1
else
printf "first num / second Num = \$(($firstNum / $secondNum))\n"
answer=$(( firstNum / secondNum))
printf "Answer = $answer\n"
fi
done
如果您有兴趣学习Bash测试语法[[]]
(它比POSIX shell的测试(1)[]
更强大),这里有一个使用的示例它:
#!/bin/bash
firstNum=0
secondNum=0
answer=0
while [[ "$firstNum" < 99 && "$secondNum" < 99 ]]
do
read -p "Enter first number " firstNum
read -p "Enter second number " secondNum
printf "first num $firstNum\n"
printf "second Num $secondNum\n"
if [[ "$secondNum" == 0 ]]
then
printf "$secondNum was a zero, exiting!\n"
exit 1
else
printf "first num / second Num = \$(($firstNum / $secondNum))\n"
answer=$(( firstNum / secondNum))
printf "Answer = $answer\n"
fi
done
建议将测试移到while
循环的主体中,而不是使用约定,而[[1]]&#39;创建一个连续循环。下面是一个示例(使用bash测试语法[[]]
)并使用bc
,因此脚本支持浮点运算:
#!/bin/bash
firstNum=0
secondNum=0
answer=0
while [[ 1 ]]
do
read -p "Enter first number " firstNum
read -p "Enter second number " secondNum
printf "first num $firstNum\n"
printf "second Num $secondNum\n"
case "$firstNum" in
99) printf "Invalid values\n"
exit 1
;;
esac
case "$secondNum" in
99) printf "Invalid values\n"
exit 1
;;
0) printf "Invalid values\n"
exit 1
;;
esac
answer=$(printf "$firstNum / $secondNum\n" | bc -l)
printf "Floating point supported answer using bc: = $answer \n"
done