Home > Net >  How do I prompt user to input two numbers and choose the arithmetic operator to use in bash script u
How do I prompt user to input two numbers and choose the arithmetic operator to use in bash script u

Time:05-19

I am trying to program a code where a user is prompted to input 2 numbers and choose an operator to execute. I tried to run this but the if statements don't work and I don't know the problem.

  echo "Enter 1st number: "
  read num1
  echo "Enter 2nd number: "
  read num2
  echo "a. Add b. Subtract c. Multiply d. Divide"
  echo "Enter Operator: "
  read opr

  if [[$opr==A]]
  then
          sum=$(($num1   $num2))
          echo "The sum is $sum."
  elif [[$opr==B]]
  then
          diff=$(($num1 - $num2))
          echo "The difference is $diff"
  elif [[$opr==C]]
  then
          prod=$(($num1 * $num2))
          echo "The product is $prod"
  elif [[$opr==D]]
  then
          quot=$(($num1 / $num2))
          echo "The quotient is $quot"
  else
          echo "Invalid. Please enter A, B, C, and D only."
  fi

CodePudding user response:

Error in [[ aside, I would recommend using a case statement instead:

case $opr in
  
  A)
      sum=$(($num1   $num2))
      echo "The sum is $sum."
      ;;
  B)
      diff=$(($num1 - $num2))
      echo "The difference is $diff"
      ;;
  C)
      prod=$(($num1 * $num2))
      echo "The product is $prod"
      ;;
  D)
      quot=$(($num1 / $num2))
      echo "The quotient is $quot"
      ;;
  *)
      echo "Invalid. Please enter A, B, C, and D only."
      ;;
esac

CodePudding user response:

You need to put spaces between double square brackets in all if statements:

if [[ $opr == A ]]

Moreover: bash is case sensitive, so if you want to match both uppercase and lowercase letters from your input request, you should use something like this:

if [[ ${opr^^} == A ]]

That above syntax converts the value of $opr variable to uppercase, whatever you typed.

CodePudding user response:

might i suggest

read -p "Enter 1st number: " num1
read -p "Enter 2nd number: " num2
echo -e "a. Add b. Subtract c. Multiply d. Divide" && read -p "Enter Operator: " opr

case $opr in
    'a'|'A')
          sum=$(($num1   $num2))
          echo "The sum is $sum.";;
    'b'|'B')
        diff=$(($num1 - $num2))
        echo "The difference is $diff";;
    'c'|'C')
        prod=$(($num1 * $num2))
        echo "The product is $prod";;
    'd'|'D')
        quot=$(($num1 / $num2))
        echo "The quotient is $quot";;
    *)
        echo "Invalid. Please enter A, B, C, and D only.";;
esac

it's a lot cleaner and achieves you're desired result.

  • Related