Bash的新手.简单的脚本 [英] new to Bash. Simple script
问题描述
我是bash脚本的新手,并且正在练习一些代码.
I am new to bash scripting and I am practicing some code.
我正在尝试创建一个脚本,该脚本显示以下输出并循环播放,直到用户键入x或X
I am trying to create a script that displays the following output and loops until the user types x or X
菜单1
C)计算
X)退出
C
菜单2
输入整数或按X退出:
22
菜单3
+)添加
-)减去
+
菜单2
输入整数或按X退出:
33
22和33的总和是55
The sum of 22 and 33 is 55
菜单1
C)计算
X)退出
c
菜单2
输入整数或按X退出:
50
菜单3
+)添加
-)减去
-
菜单2 输入一个整数或按X退出:
Menu 2 Enter an integer or press X to exit:
23
50和23的差是27
The difference of 50 and 23 is 27
菜单1
C)计算
X)退出
X
这是我的代码:
add ()
{
((sum=n1 + n2))
echo "The sum of $n1 and $n2 is $sum"
exit
}
subtract ()
{
((difference=n1 - n2))
echo "The difference of $n1 and $n2 is $difference"
exit
}
while true
do
echo "Menu 1"
echo "C) Calculation"
echo "X) Exit"
read opr
if [ ${opr} = 'x' ] || [ ${opr} = 'X' ]
then
break
elif [ ${opr} = 'c' ] || [ ${opr} = 'C' ]
then
echo "Menu 2"
echo "Enter an integer or press X to exit:"
fi
read n1
if [ $n1 = 'x' ] || [ $n1 = 'X' ]
then
break
else
echo "Menu3"
echo "+) Add"
echo "-) Subtract"
fi
read opr
if [ $opr = '+' ]
then
echo "Please enter another integer to perform addition"
read n2
add
elif [ $opr = '-' ]
echo "Please enter another integer to perform subtraction"
read n2
subtract
fi
done
我收到此错误消息:
./myscript.sh:第72行:意外令牌fi'
./myscript.sh: line 72:
fi'
./myscript.sh: line 72: syntax error near unexpected token fi'
./myscript.sh: line 72:
fi'
我相信,如果将menu1,menu2和menu3设置为函数,则可以实现我希望输出的内容而不是此版本的输出.
I believe if I make menu1, menu2, and menu3 into functions I could achieve what I desire my output to be instead of this version of it.
但是我知道我仍然会对那些文件有问题……任何想法我应该把它们放在哪里,或者我需要做什么才能使我的代码正常工作而不给出错误?
But I know that I will still have a problem with those fi ... any idea where I should put them or what do I need to do for my code to work and not give an error?
谢谢
药丸
推荐答案
您只是在elif
在 http://www.thegeekstuff中查找一般示例. com/2010/06/bash-if-statement-examples/
If [ conditional expression1 ]
then
statement1
statement2
.
elif [ conditional expression2 ]
then
statement3
statement4
.
.
.
else
statement5
fi
在您的代码中:
...
elif [ $opr = '-' ]
then <<<<<<< missing in your code!
echo "Please enter another integer to perform subtraction"
read n2
subtract
fi
为什么程序没有循环
如果在add
和subtract
方法中编写exit
,则脚本将退出.为什么不应该呢?提示:删除exit
和循环都有机会:-)
If you write exit
in your add
and subtract
method, your script will exit. Why it should not? Tip: remove both exit
and the loop have a chance :-)
这篇关于Bash的新手.简单的脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!