簡體   English   中英

Unix - 使用 shell 腳本的簡單計算器 [已編輯]

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM