我的带有加法函数的脚本不会对我根据读取分配数值的两个变量执行加运算符 (+)。使用其他运算符,其他功能将正常工作。
脚本:
#!/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 将退出。