関数に入力された引数の数を制御する方法

関数に入力された引数の数を制御する方法

簡単なメニューベースの電卓スクリプトを作成しようとしています。ユーザーが正しいパラメータを入力せずにadd()またはminus()関数を呼び出すたびに、エラーメッセージを表示したいと思います。 3つ以上のパラメータ(演算子を含む)、パラメータなし(0と等しい)、無効な演算子(減算または減算ではありません)など

#はコマンドラインに入力された引数を意味するので、その部分が間違っていることを知っていますが、関数に入力された引数を確認する方法がわかりません。

#!/bin/bash  
display() {
echo "Calculator Menu" 
echo "Please select an option between add, subtract or exit"
echo "A. Add"
echo "B. Subtract"
echo "C. Exit"
} 
#initialize choice n
choice=n 

if [ $# > 3 ] 
then 
echo " You need to input 3 parameters. "
fi

if [ $# -eq 0 ]
then 
echo " You have not entered any parameters, please input 3. "
fi 

if  [ $2 != "+" ] || [ $2 != "-" ]
then
echo " Please enter an add or subtract operator."
fi


add() {
echo " The sum of $one + $three equals $(( $one $op $three ))"
}

subtract () {
echo " The difference of $one - $three equals $(( $one $op $three )) "
} 

while [ $choice != 'C' ] 
do display
read choice
if [ $choice = 'A' ] 
then 
read -p "Please enter two operands and the operator '+': " one op three
add $one $op $three

elif [ $choice = 'B' ] 
then
read -p " Please enter two operands and the operator '-': " one op three
subtract $one $op $three

elif [ $choice = 'C' ]
then
echo "Thank you for using this program. The program will now exit." 
fi 

done
 


sleep 3

exit 0

ベストアンサー1

$#まだあなたが望むもの。これには、コマンドラインの関数またはスクリプトに渡された位置引数の数が含まれます。位置パラメータセクションを参照してください。内部変数

たとえば、add次のように関数を変更します。

add() {
    if [ $# -ne 3 ]
    then
            echo " ERROR: Incorrect number of arguments"
            return 1
    fi
    echo " The sum of $one + $three equals $(( $one $op $three ))"
}

(引数1個)についてはエラーが返されますが(引数3個)の計算結果が返されます2+22 + 2

たぶんあなたは方法を尋ねたいかもしれません。呼ぶadd関数の3つのテストにはsubtractパラメータが含まれています。この場合、これらのテストを他の関数にラップします。

test_args() {
    if [ $# > 3 ]
    ...12 lines omitted...
    fi
}

$@同じパラメータをすべてtest_args関数に渡すために使用されます。たとえば、

add() {
    test_args $@
    echo " The sum of $one + $three equals $(( $one $op $three ))"
}

おすすめ記事