How to handle invalid operations?

QuestionsQuestions8 SkillsProShell FunctionsNov, 10 2025
0104

To handle invalid operations in a function like ENGLISH_CALC, you can use a case statement to check for valid operations and provide a default case to manage any invalid input. Here’s an example:

ENGLISH_CALC() {
    local operation=$1
    local num1=$2
    local num2=$3

    case $operation in
        add)
            echo $((num1 + num2))
            ;;
        subtract)
            echo $((num1 - num2))
            ;;
        multiply)
            echo $((num1 * num2))
            ;;
        divide)
            if [ $num2 -ne 0 ]; then
                echo $((num1 / num2))
            else
                echo "Error: Division by zero is not allowed."
            fi
            ;;
        *)
            echo "Error: Invalid operation. Please use add, subtract, multiply, or divide."
            ;;
    esac
}

In this code:

  • The case statement checks the operation variable.
  • If the operation is not one of the recognized commands (add, subtract, multiply, divide), it falls to the default case (*), which prints an error message indicating that the operation is invalid.
  • Additionally, for the divide operation, it checks if num2 is zero to prevent division by zero, providing a specific error message for that case.

0 Comments

no data
Be the first to share your comment!