構文エラー:オペランドが必要です(エラーは「= 1 +」と表示されます)。

構文エラー:オペランドが必要です(エラーは「= 1 +」と表示されます)。

私はシェルスクリプトに初めて触れましたが、なぜこのエラーが発生するのかわかりません。プログラムを実行して減算を選択すると、同じ場所の次のサブ関数でエラーが発生します。コード全体を公開しましたが、最初の2つの関数(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))

おすすめ記事