Calculator Program in Shell Script using Switch Case
A web-based simulator and guide for creating a command-line calculator in Bash.
Interactive Shell Script Calculator Simulator
The first numeric value for the operation.
Choose the arithmetic operation, simulating the ‘case’ in the script.
The second numeric value for the operation.
Visual Representation
What is a Calculator Program in Shell Script using Switch Case?
A calculator program in shell script using switch case is a command-line tool, typically written for a Unix-like environment (like Linux or macOS), that performs basic arithmetic operations. Instead of a graphical interface, it uses text-based prompts. The “switch case” (known as `case…esac` in shell scripting) is the core logic that checks which operation the user wants to perform (e.g., addition, subtraction) and executes the corresponding calculation. This type of program is an excellent beginner project for learning the fundamentals of shell scripting, including variable handling, user input, and conditional logic. Many developers prefer a linux command line calculator for its speed and integration into their workflow.
The ‘case…esac’ Formula for a Shell Script Calculator
The “formula” for this type of program is the script’s code structure itself. The `case` statement is a control flow mechanism that allows you to match a variable against several possible patterns. It provides a cleaner alternative to using multiple `if…elif…else` statements.
Here is a complete, functional example of a calculator program in shell script using switch case:
#!/bin/bash
echo "Simple Shell Calculator"
echo "Enter the first number:"
read num1
echo "Enter the second number:"
read num2
echo "Choose an operation:"
echo "1. Addition (+)"
echo "2. Subtraction (-)"
echo "3. Multiplication (*)"
echo "4. Division (/)"
read choice
case $choice in
1)
result=$((num1 + num2))
echo "Result: $num1 + $num2 = $result"
;;
2)
result=$((num1 - num2))
echo "Result: $num1 - $num2 = $result"
;;
3)
result=$((num1 * num2))
echo "Result: $num1 * $num2 = $result"
;;
4)
if [ "$num2" -eq 0 ]; then
echo "Error: Division by zero is not allowed."
else
result=$(echo "scale=2; $num1 / $num2" | bc)
echo "Result: $num1 / $num2 = $result"
fi
;;
*)
echo "Invalid choice. Please select 1, 2, 3, or 4."
;;
esac
Variables Table
| Variable | Meaning | Unit | Typical Range |
|---|---|---|---|
num1 |
The first number provided by the user. | Numeric (Integer/Float) | Any valid number |
num2 |
The second number provided by the user. | Numeric (Integer/Float) | Any valid number (non-zero for division) |
choice |
The user’s selection for the arithmetic operation. | Integer (1-4) | 1, 2, 3, 4 |
result |
The stored outcome of the calculation. | Numeric | Varies based on input |
For more complex operations, a deeper dive into a bash case statement guide can be very helpful.
Practical Examples
Example 1: Addition
- Inputs: num1 = 150, num2 = 350
- Operation Choice: 1 (Addition)
- Units: Numeric (unitless)
- Result: 500
Example 2: Division
- Inputs: num1 = 100, num2 = 8
- Operation Choice: 4 (Division)
- Units: Numeric (unitless)
- Result: 12.50 (Note: The script uses `bc` for floating-point division)
How to Use This Shell Script Calculator
- Save the Code: Copy the code above and save it into a file named `calculator.sh`.
- Make it Executable: Open your terminal and run the command `chmod +x calculator.sh`. This gives the script permission to run.
- Run the Script: Execute the script by typing `./calculator.sh` in your terminal.
- Follow the Prompts: The script will ask you to enter two numbers and then choose an operation. The result will be displayed directly in your terminal. For an alternative approach, you might want to learn more from a bash scripting tutorial.
Key Factors That Affect a Shell Script Calculator
- Integer vs. Floating-Point Math: Standard Bash only supports integer arithmetic. For division or calculations involving decimals, an external utility like `bc` (Basic Calculator) is required, as shown in the example.
- Input Validation: The script should always check if the user’s input is valid. This includes checking for non-numeric inputs and ensuring the divisor is not zero.
- Error Handling: A robust script provides clear error messages, such as “Invalid choice” or “Division by zero.”
- User Experience: Clear prompts and well-formatted output make the command-line tool easier to use.
- Code Readability: Using comments and meaningful variable names makes the script easier to maintain and understand, which is a core part of any good shell programming guide.
- Modularity: For more complex calculators, breaking the code into functions (e.g., a function for each operation) can improve organization.
Frequently Asked Questions (FAQ)
Why use a `case` statement instead of `if-elif-else`?
A `case` statement is often more readable and efficient when you are comparing a single variable against multiple possible values. It’s a cleaner way to structure the selection logic than a long chain of `if` statements.
What does `#!/bin/bash` mean?
This is called a “shebang.” It specifies the interpreter that should be used to execute the script. In this case, it tells the system to use the Bash shell.
How does floating-point math work in a bash script calculator?
Bash itself can’t handle decimals. To perform floating-point calculations, you must pipe the expression to an external command-line utility like `bc`. The command `echo “scale=2; 10 / 3” | bc` tells `bc` to calculate `10 / 3` with a precision of 2 decimal places.
What does `read choice` do?
The `read` command pauses the script and waits for the user to type something and press Enter. The input is then stored in the variable specified (in this case, `choice`).
What is the purpose of `;;` in the `case` statement?
The double semicolon `;;` terminates each block of commands within the `case` statement, similar to the `break` keyword in other programming languages. It prevents the script from “falling through” and executing the commands in the next case.
Can I pass numbers as arguments instead of using prompts?
Yes. You could modify the script to accept command-line arguments (e.g., `./calculator.sh 10 + 5`). You would access these values using special variables like `$1`, `$2`, and `$3`.
How can I handle more complex operations like square roots?
For advanced math, you would rely more heavily on the `bc` utility with its math library. For example, `echo “sqrt(16)” | bc -l` would calculate the square root of 16.
Is a `case…esac` statement the same as a switch case?
Yes, `case…esac` is the Bash shell’s equivalent of the switch-case structure found in languages like C++, Java, and JavaScript. Understanding this is key to mastering advanced bash scripting techniques.
Related Tools and Internal Resources
Explore these resources for more information on shell scripting and command-line tools:
- Learn Shell Scripting from Scratch: A beginner’s guide to the fundamentals.
- Data Processing with Awk: A powerful tool for text manipulation.
- Introduction to Sed: Learn about the stream editor for filtering and transforming text.