Four Function Calculator

ShellBeginner
Practice Now

Introduction

In this challenge, you'll create a basic four-function calculator in a shell script. This will help you understand the fundamentals of defining and using multiple functions in shell scripting.

Create Calculator Functions

Tasks

  1. Navigate to the ~/project directory where you'll find a partially completed script named calculator.sh.
  2. Open the calculator.sh file and complete the four functions: add, subtract, multiply, and divide.

Requirements

  • The script calculator.sh is already created in the ~/project directory with a basic structure.
  • Your task is to complete the following functions:
    • add: Takes two parameters and returns their sum.
    • subtract: Takes two parameters and returns the result of subtracting the second from the first.
    • multiply: Takes two parameters and returns their product.
    • divide: Takes two parameters and returns the result of dividing the first by the second. Remember to handle division by zero.
  • Each function should take two parameters and echo the result.
  • The main part of the script (which calls the functions) is already provided.
  • Important Note: In the case statement, all operation symbols (+, -, *, /) are enclosed in quotes to prevent shell interpretation. The * symbol without quotes acts as a wildcard and would match any input, causing unexpected behavior.

Example

Here's an example of how the completed script should work:

$ ./calculator.sh
Enter first number: 10
Enter second number: 5
Enter operation (+, -, *, /): +
Result: 15

$ ./calculator.sh
Enter first number: 10
Enter second number: 5
Enter operation (+, -, *, /): -
Result: 5

$ ./calculator.sh
Enter first number: 10
Enter second number: 5
Enter operation (+, -, *, /): *
Result: 50

$ ./calculator.sh
Enter first number: 10
Enter second number: 5
Enter operation (+, -, *, /): /
Result: 2

$ ./calculator.sh
Enter first number: 10
Enter second number: 0
Enter operation (+, -, *, /): /
Error: Division by zero is not allowed.

The script's strings must reference the examples and remain unchanged to prevent test failures.

Summary

In this challenge, you created a four-function calculator using shell scripting. You practiced defining multiple functions that take parameters, perform calculations, and return results. This exercise reinforced your understanding of basic function declaration and usage in shell scripts, demonstrating practical applications for simple computations and error handling.

✨ Check Solution and Practice