0

I am trying to make a simple menu-driven calculator script. I am trying to make it such that after selecting A (add) or B (subtract) from the menu, it'll call the function and display the corresponding message when:

  1. The parameters entered when function called is greater than 3
  2. No parameters are entered when the function is called
  3. The operator entered when the function is called is neither "+" or "-"

Right now it is doing the parameter check when I call the script ./mycalc.sh executing the script

Am not sure how to make it check parameters after the function is called?

#!/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 [[ $# -ne 3 ]]
then echo " You have not entered 3 parameters" 
exit 1
fi

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

if  [[ $2 != [+-] ]]
then
echo " Please enter an add or subtract operator."
exit 1
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 Answers1

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

Within [...], the > is simply redirection. You'll find an empty file named 3 in your current directory.

Since this is an error condition for your script, you'll want to exit:

if [[ $# -ne 3 ]]; then
    echo "usage: $0 operand1 operator operand2" >&2
    exit 1
fi

And to test the operator, there are many ways.

  • case, but it's a bit verbose

    case $2 in 
        '+'|'-') : ;;
        *)  echo "Operator must be + or -" >&2
            exit 1
            ;;
    esac
    
  • Within [[...]] the == and != operators are pattern matching operators

    if [[ $2 != [+-] ]]; then  
        echo "Operator must be + or -" >&2
        exit 1
    fi
    
glenn jackman
  • 238,783
  • 38
  • 220
  • 352