如何控制输入到函数中的参数数量

如何控制输入到函数中的参数数量

我正在尝试制作一个简单的菜单驱动计算器脚本。我希望每当用户调用 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 ))"
}

将为(一个参数)返回错误,但会返回(三个参数)2+2的计算结果。2 + 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 ))"
}

相关内容