我的帶有加法函數的腳本不會對我根據讀取分配數值的兩個變數執行加運算子 (+)。使用其他運算符,其他功能將正常運作。
腳本:
#!/bin/bash
function addition {
FNUM1=$1
FNUM2=$2
RESULT=$((FNUM1+FNUM2))
echo "RESULT: $RESULT"
}
function subtraction {
FNUM1=$1
FNUM2=$2
RESULT=$((FNUM1-FNUM2))
echo "RESULT: $RESULT"
}
function multiplication {
FNUM1=$1
FNUM2=$2
RESULT=$((FNUM1*FNUM2))
echo "RESULT: $RESULT"
}
function division {
FNUM1=$1
FNUM2=$2
RESULT=$((FNUM1/FNUM2))
echo "RESULT: $RESULT"
}
clear
echo "Please select a calculation to make!"
echo "Choose how to you want to calculate two numbers"
COUNTER=0
while [ $COUNTER -eq 0 ]
do
echo ""
echo "1 - addition"
echo "2 - subtraction"
echo "3 - multiplication"
echo "4 - division"
echo "5 - QUIT"
read CHOICE
case $CHOICE in
1)
echo "YOU CHOSE ADDITION!"
echo "Enter first number: "
read NUM1
echo "Added by: "
read NUM2
addition $NUM1 $NUM
;;
2)
echo "YOU CHOSE SUBTRACTION!"
echo "Enter first number: "
read NUM1
echo "Subtracted by: "
read NUM2
subtraction $NUM1 $NUM2
;;
3)
echo "YOU CHOSE MULTIPLICATION!"
echo "Enter first number: "
read NUM1
echo "Multiplied by: "
read NUM2
multiplication $NUM1 $NUM2
;;
4)
echo "YOU CHOSE DIVISION!"
echo "Enter first number: "
read NUM1
echo "Divided by: "
read NUM2
division $NUM1 $NUM2
;;
5)
COUNTER=$(( $COUNTER + 1 ))
;;
*)
echo "You must enter a number from 1 through 5!"
esac
done
輸出:
Please select a calculation to make!
Choose how to you want to calculate two numbers
1 - addition
2 - subtraction
3 - multiplication
4 - division
5 - QUIT
1
YOU CHOSE ADDITION!
Enter first number:
24
Added by:
5
RESULT: 24
我希望加法函數將讀取到 FNUM1 和 FNUM2 變數中的值相加。
答案1
正如 ilkkachu 評論的那樣,您的添加程式碼中有一個簡單的拼字錯誤:
echo "Added by: "
read NUM2
addition $NUM1 $NUM
應該:
echo "Added by: "
read NUM2
addition $NUM1 $NUM2
同上 ShellCheck 的評論建議和set -u
對於此類錯誤。set -u
執行腳本時會給你一個錯誤。
執行參數擴展時,將除特殊參數“@”或“*”之外的未設定變數和參數視為錯誤。錯誤訊息將寫入標準錯誤,並且非互動式 shell 將退出。