语法错误:需要操作数(错误标记为“=1 +”)

语法错误:需要操作数(错误标记为“=1 +”)

我是 shell 脚本新手,不确定为什么会收到此错误。如果我运行程序并选择减法,则错误会发生在同一位置的下一个子函数处。我已经发布了整个代码,但我认为错误仅存在于前两个函数(add() 和 sub() 中)。

任何关于为什么会发生这种情况的解释将不胜感激。谢谢

function add(){
echo "mycalc $1 + $2" 
(($sum = $1 + $2))
echo "The sum of $1 plus $2 is $sum" 
sleep 3
clear
exit
}

function sub(){
echo "mycalc $1 - $2" 
(($sub = $1 - $2))
echo "$1 minus $2 equals $sub" 
sleep 3
clear
exit
}

choice=a

if [ $# = 3 ] && [ "$2" = '+' ] || [ "$2" = '-' ]
then if 
[ "$2" = '+' ] && [ "$1" -le 0 ] || [ "$1" -ge 0 ] && [ "$3" -le 0 ] || [ "$3" -ge 0 ]
then add $1 $3

elif
[ "$2" = '-' ] && [ "$1" -le 0 ] || [ "$1" -ge 0 ] && [ "$3" -le 0 ] || [ "$3" -ge 0 ]
then sub $1 $3
else
echo "Main Menu"
sleep 3
clear
fi
else while [ $choice != "X" ] && [ $choice != "x" ]
do
echo "Please choose one of the following options" 
echo "C) Calculate " 
echo "X) Exit" 
read -p "Option" choice

if [ $choice = "C" ] || [ $choice = "c" ]
then choice1=a
while [ $choice1 != "X" ] && [ $choice1 != "x" ] 
do
read -p "Please enter an integer or press X to exit." choice1

if [ $choice1 = "X" ] || [ $choice1 = "x" ]
then
echo "Good bye" 
sleep 3
clear
exit

elif [ $choice1 -le 0 ] || [ $choice1 -ge 0 ]
then action=a
while [ $action != "X" ] && [ $action != "x" ] 
do
echo "Please select an operation"
echo "+) Addition" 
echo "-) Subtraction" 
echo "X) Exit" 
read action

if [ $action = "X" ] || [ $action = "x" ]
then
echo "Good bye" 
sleep 3
clear
exit

elif [ "$action" = "+" ] || [ "$action" = "a" ] || [ "$action" = "A" ]
then
read -p "Please enter another number " num2
add $1 $num2
elif [ $action = "-" ] || [ $action = s ] || [ $action = "S" ]
then
read -p "Please enter another number " num2
sub $1 $num2

else
echo "Invalid response, please try again" sleep 3 
clear
fi
done

else
echo "Invalid response" 
sleep 3
clear
fi
done

elif [ choice = "X" ] || [ choice = "x" ]
then
echo "Good bye" 
sleep 3
clear
exit

else
echo "Invalid response"
sleep 3
clear
fi
done
fi
                                                          117,1         Bot

答案1

错误在于(($sum = $1 + $2))在 bash 脚本中添加数字

使用算术展开

对于整数:

sum=$(($1 + $2))
sub=$(($1 - $2))

答案2

除了算术扩展之外,计算数字运算的另一种方法是使用 shell 内置 keywrod let

let sum=$1+$2
let sub=$1-$2

有关此关键字的更多信息:help letman bash

相关内容