[英]Unix - simple Calculator using shell scripting [edited]
我刚开始在 Unix 操作系统中使用 shell 编写一个简单的脚本,我尝试先编写一个简单的计算器代码,该代码让用户选择一个操作(加法、减法等),它将被保存为一个变量(选择)然后,让用户插入任意两个数字,这些数字将被保存为变量(num1 和 num2) 最后,执行操作,检查代码以获取更多信息
echo "+--------------------+"
echo "| Simple Calculator |"
echo "+--------------------+"
echo "This shell is a simple calculator that takes two numbers from user, perform math operation then return the results"
echo Please choose an operation from the following:
echo 1,Addition
echo 2,Subtraction
echo 3,Multiplication
echo 4,division
echo Please choose an operation
read choice
echo Please insert the 1st number:
read num1
echo Please insert the 2ed number:
read num2
case $choice
1) echo "The result of addition operation is:`expr $num1 + $num2`;;
2) echo The result of Subtraction operation is:`expr $num1 - $num2`;;
3) echo The result of Multiplication operation is:`expr $num1 \* $num2`;;
4) echo The result of Division operation is:`expr $num1 \/ $num2`;;
*) echo invalid operation, please try again;;
esac
不幸的是,即使我做了一些更改,代码仍然无法正常工作,它一直显示此错误:
./shell.sh: line 16: syntax error near unexpected token 1'./shell.sh: line 16:
1) echo 加法运算结果为: expr $num1 + $num2
;;'
注意:此代码不适用于大学项目,也不适用于我探索和学习的家庭作业。
您的case
语法错误。
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_03.html
解释如何用case
; 因为你想做的事情并没有从你的源代码中变得清晰,所以我真的不能给你太多关于如何做的信息:(
为了娱乐:
#!/bin/bash
echo "Better calculator"
while read -r -p 'Enter expression (CTRL-C or CTRL-D for end)> ' exp
do
echo "$exp =" $(bc -l <<< "$exp")
done
或者直接输入命令提示符:
bc -l
但可能你的老师想要不同的东西...... :)
所以我现在知道我的错误了:D
我的错误在第 15 行,我应该在选择后输入“in”
"case $choose in" --> 这在你使用 "case" 时非常重要
简单吧! --> 这让我疯狂了一阵子"^__^
echo "+--------------------+"
echo "| Simple Calculator |"
echo "+--------------------+"
echo "This shell is a simple calculator that takes two numbers from user, perform math operation then return the results"
echo Please choose an operation from the following:
echo 1,Addition
echo 2,Subtraction
echo 3,Multiplication
echo 4,division
echo Please choose an operation
read choice
echo Please insert the 1st number:
read num1
echo Please insert the 2ed number:
read num2
case $choice
1) echo "The result of addition operation is:`expr $num1 + $num2`;;
2) echo The result of Subtraction operation is:`expr $num1 - $num2`;;
3) echo The result of Multiplication operation is:`expr $num1 \* $num2`;;
4) echo The result of Division operation is:`expr $num1 \/ $num2`;;
*) echo invalid operation, please try again;;
esac
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.