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.
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.
~/project
directory where you'll find a partially completed script named calculator.sh
.calculator.sh
file and complete the four functions: add
, subtract
, multiply
, and divide
.calculator.sh
is already created in the ~/project
directory with a basic structure.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.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.
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.