Shell Script Calculator Program using If-Else
An interactive tool that demonstrates how a basic calculator program in shell script using if else logic works. Enter two numbers, choose an operation, and see the result calculated instantly.
What is a Calculator Program in Shell Script Using If Else?
A calculator program in shell script using if else is a simple command-line tool written in a shell scripting language (like Bash) that performs basic arithmetic operations. The user provides two numbers and an operator (like ‘+’, ‘-‘, ‘*’, ‘/’), and the script uses a series of `if`, `elif` (else if), and `else` statements to determine which calculation to perform. This type of program is a classic beginner’s project in shell scripting as it effectively teaches fundamental concepts like user input, variables, and conditional logic.
Unlike compiled programs, a shell script is a text file containing a sequence of commands for a command-line interpreter. The `if-else` structure is the core decision-making mechanism, allowing the script to follow different execution paths based on the user’s chosen operator. This makes it a perfect example for understanding how to control program flow in Linux and Unix environments.
Shell Script Formula and Explanation
The “formula” for a calculator program in shell script using if else is not a single mathematical equation, but rather a programming structure. The logic relies on conditional statements to select the correct arithmetic operation. Below is the fundamental structure of such a script in Bash.
#!/bin/bash # Read inputs echo "Enter first number:" read num1 echo "Enter second number:" read num2 echo "Enter operator (+, -, *, /):" read op # Conditional logic if [ "$op" == "+" ]; then result=$((num1 + num2)) elif [ "$op" == "-" ]; then result=$((num1 - num2)) elif [ "$op" == "*" ]; then result=$((num1 * num2)) elif [ "$op" == "/" ]; then result=$((num1 / num2)) else echo "Invalid operator" exit 1 fi echo "Result: $result"
Variables Table
| Variable | Meaning | Unit | Typical Range |
|---|---|---|---|
num1 |
The first operand in the calculation. | Unitless Number | Any integer or floating-point number. |
num2 |
The second operand in the calculation. | Unitless Number | Any integer or floating-point number. |
op |
The arithmetic operator chosen by the user. | Character | ‘+’, ‘-‘, ‘*’, ‘/’ |
result |
The outcome of the arithmetic operation. | Unitless Number | Dependent on the inputs and operator. |
For more advanced scripting, check out this guide on bash script tutorial to improve your skills.
Practical Examples
Let’s see how the script processes a couple of real-world scenarios. These examples illustrate the flow of logic through the `if-elif-else` structure.
Example 1: Addition
- Inputs:
num1 = 100,num2 = 50,op = + - Logic: The script checks `if [ “$op” == “+” ]`. This condition is true.
- Result: It executes
result=$((100 + 50)), and the final output is 150.
Example 2: Division
- Inputs:
num1 = 99,num2 = 3,op = / - Logic: The script skips the `if` and first two `elif` blocks. The condition `elif [ “$op” == “/” ]` is true.
- Result: It executes
result=$((99 / 3)), and the final output is 33.
How to Use This Shell Script Calculator
This interactive tool simulates a command-line calculator program in shell script using if else. Follow these steps to use it:
- Enter First Number: Type the first number for your calculation into the “First Number” field.
- Select Operator: Choose the desired arithmetic operation (+, -, *, /) from the dropdown menu. This simulates user input for the operator.
- Enter Second Number: Type the second number into the “Second Number” field.
- Calculate: As you change the inputs, the result is automatically calculated and displayed in the “Calculation Result” box, mimicking the script’s output.
- Interpret Results: The primary result is shown prominently. The “Simulated Shell Script Logic” section shows the specific `if/elif` block that would be executed in a real script to get that result. This is a great way to understand shell scripting basics.
Key Factors That Affect a Shell Script Calculator
When writing or using a calculator program in shell script using if else, several factors can influence its behavior and accuracy.
- Integer vs. Floating-Point Arithmetic: By default, Bash shell arithmetic handles integers only. Dividing 7 by 2 would result in 3, not 3.5. For floating-point (decimal) calculations, external tools like `bc` (Basic Calculator) must be used within the script.
- Input Validation: The script should check if the user entered actual numbers. Without validation, trying to calculate “cat + dog” would throw an error.
- Division by Zero: A robust script must explicitly check if the user is attempting to divide by zero, as this is an undefined operation that will cause an error.
- Operator Handling: The `if-elif-else` structure must correctly handle all expected operators and have a final `else` block to catch any invalid inputs (e.g., ‘%’, ‘^’).
- Use of Quotes: Variables in shell scripts should be double-quoted (e.g., `”$op”`) to prevent unexpected behavior with spaces or special characters. Understanding this is part of learning to write your first script.
- Command-Line Arguments vs. Interactive Input: The calculator can be designed to accept numbers as command-line arguments (`./calc.sh 5 + 2`) or interactively using the `read` command. Each approach requires a different script structure.
Frequently Asked Questions (FAQ)
1. Why use `if-elif-else` instead of a `case` statement?
Both `if-elif-else` and `case` statements can be used to build a calculator. The `if-elif-else` structure is often taught first as it is a more fundamental conditional concept. A `case` statement can be cleaner and more readable if you have many operators to check against.
2. How do I handle decimal numbers in a shell script calculator?
Standard Bash arithmetic `((…))` does not support floating-point numbers. You must pipe the expression to the `bc` (basic calculator) command: `result=$(echo “scale=2; $num1 / $num2” | bc)`. The `scale` variable sets the number of decimal places.
3. What does `#!/bin/bash` mean?
This is called a “shebang.” It’s the first line in the script and tells the operating system which interpreter to use to run the file’s commands, in this case, the Bash shell. It’s a key part of any command line calculator.
4. How do I check for non-numeric input?
You can use a regular expression within an `if` statement to test if the input contains only digits. For example: `if ! [[ “$num1” =~ ^[0-9]+$ ]]; then echo “Error: Not a number”; fi`.
5. Why are my variables in square brackets `[ … ]`?
The single square bracket `[` is an alias for the `test` command. It is used to evaluate conditional expressions, such as comparing two strings or numbers. For example, `[ “$op” == “+” ]` tests if the value of the `op` variable is equal to “+”.
6. Can I combine conditions in an `if` statement?
Yes, you can use logical operators like `-a` (AND) and `-o` (OR) within single brackets, or `&&` (AND) and `||` (OR) with double brackets `[[ … ]]` to test multiple conditions at once.
7. What is the difference between `=` and `-eq` for comparisons?
Inside single or double square brackets, `=` is used for string comparison, while `-eq` is used for numerical equality. For example, `[ “5” -eq “05” ]` is true, but `[ “5” == “05” ]` is false.
8. How do I make my shell script executable?
After saving your script (e.g., `calculator.sh`), you need to give it execute permissions using the command `chmod +x calculator.sh`. Then you can run it with `./calculator.sh`.
Related Tools and Internal Resources
Explore more of our tools and tutorials to enhance your command-line and development skills.
- Bash Scripting Basics: A comprehensive guide for anyone new to shell scripting.
- Regular Expression Tester: Test your regex patterns, which are useful for input validation in scripts.
- Understanding Linux Permissions: Learn what `chmod +x` really does and how file permissions work.
- Writing Your First Script: A step-by-step tutorial for beginners.
- CHMOD Calculator: Easily determine the right numeric codes for file permissions.
- Advanced Shell Scripting Topics: Dive deeper into functions, arrays, and more complex scripting techniques.