【发布时间】:2021-05-24 06:12:59
【问题描述】:
#!/bin/bash
while true
do
if [[ $# -eq 0 ]] ; then
echo Enter operand1 value:
read operand1
# Offer choices
echo 1. Addition
echo 2. Subtraction
echo 3. Multiplication
echo 4. Division
echo 5. Exit
echo Enter your choice:
read choice
if [[ $choice != 1 || 2 || 3 || 4 || 5 ]] ; then
echo Sorry $choice is not a valid operator - please try again
echo Enter your choice:
read choice
else
Continue
fi
echo Enter operand2 value:
read operand2
# get operands and start computing based on the user's choice
if [[ $choice -eq 1 ]] ; then
echo ----------------------------------------
echo Addition of $operand1 and $operand2 is $((operand1+operand2))
echo ----------------------------------------
echo
elif [[ $choice -eq 2 ]] ; then
echo ----------------------------------------
echo Subtraction of $operand1 and $operand2 is $((operand1-operand2))
echo ----------------------------------------
echo
elif [[ $choice -eq 3 ]] ; then
echo ----------------------------------------
echo Multiplication of $operand1 and $operand2 is $((operand1*operand2))
echo ----------------------------------------
echo
elif [[ $choice -eq 4 && operand2 -eq 0 ]] ; then
echo Can not divide by 0 please try again
echo Please enter operand2
read operand2
echo ----------------------------------------
echo Division of $operand1 and $operand2 is $((operand1/operand2))
echo ----------------------------------------
echo
elif [[ $choice -eq 4 && operand2 -ne 0 ]] ; then
echo ----------------------------------------
echo Division of $operand1 and $operand2 is $((operand1/operand2))
echo ----------------------------------------
echo
elif [[ $choice -eq 5 ]] ; then
exit
else
echo ----------------------------------------
echo Invalid choice.. Please try again
echo ----------------------------------------
echo
fi
else
echo ----------------------------------------
echo You either passed too many parameters or too less
echo than the optimum requirement.
echo
echo This program accepts a maximum of 2 arguments or no
echo argument at all in order to run successfully.
echo ----------------------------------------
fi
done
我希望在上面的代码中添加功能,以便每个后续操作都将使用以前的结果,提示用户输入下一个运算符和操作数,这样用户就不必再次输入第一个操作数,而且很简单将其存储在内存中。我似乎想不出任何方法来做到这一点 - 有什么建议吗?
【问题讨论】:
-
问:你想一遍又一遍地使用“operand1”的相同值……还是想在后续的第一个操作数中使用result操作?在任何一种情况下:只需使用 shell 变量。 将结果分配给变量 ...而不是仅仅打印它。 Here 是检查 Bash 变量是否已分配的方法。
-
问题中的代码应该是minimal reproducible example -- 演示特定问题的最短的可能。为什么有五个选项和一堆
echos?除此之外,尚不清楚为什么您在跨迭代存储值时遇到问题 - 您设置的变量保留在原地,那么当您尝试时出现的具体问题是什么? -
顺便说一句,
[[ $choice != 1 || 2 || 3 || 4 || 5 ]]始终为真,因为在检查[[ $choice != 1 ]](可能为真或假)后,它检查[[ 2 ]],它始终为真(因为它等同于@987654329 @,而2不是空字符串)。 -
感谢@CharlesDuffy 指出这一点,我现在明白了。你能推荐一种格式化的方法吗?我一直在尝试输入一行,向用户显示他们输入了一个不正确的操作符,这是唯一一个真正与我的脚本一起工作的操作符。任何朝着正确方向推动的帮助都会非常有帮助
-
问题的上述方面与Compare string to multiple correct values重复。