Welcome back to our shell scripting series! After tackling conditional logic with if statements, it's time to explore one of the most fundamental parts of any programming language: arithmetic operations.
Today, we'll write a simple, clean, and robust shell script that acts as a basic calculator. It will ask the user for two numbers and then perform all five basic arithmetic operations: Addition (+), Subtraction (-), Multiplication (*), Division (/), and Modulus (%).
This is a fantastic exercise to learn about user input, variables, and a special, modern syntax for doing math in Bash: $((...)).
Let's get started!
The Shell Script
First, here is the complete, commented script. This script is "robust" because it includes a special check to prevent a "division by zero" error, a common bug that can crash scripts.
#!/bin/bash
# This script performs all 5 basic arithmetic operations
# on two user-provided numbers.
# 1. Prompt the user for two numbers
# 'read -p' combines echo and read into one line
read -p "Enter the first number (a): " num1
read -p "Enter the second number (b): " num2
echo "------------------------------------"
echo "You entered: a = $num1 and b = $num2"
echo "Calculating..."
echo "------------------------------------"
# 2. Perform and Display Safe Operations (Add, Subtract, Multiply)
# We use '$((...))' for arithmetic expansion.
sum=$((num1 + num2))
diff=$((num1 - num2))
product=$((num1 * num2))
echo "$num1 + $num2 = $sum"
echo "$num1 - $num2 = $diff"
echo "$num1 * $num2 = $product"
# 3. Perform and Display Unsafe Operations (Divide, Modulus)
# We must check for division by zero!
if [ $num2 -eq 0 ]; then
# -eq means "is equal to"
echo "$num1 / $num2 = Error: Division by zero is not allowed."
echo "$num1 % $num2 = Error: Division by zero is not allowed."
else
# This block only runs if $num2 is not zero
quotient=$((num1 / num2))
remainder=$((num1 % num2))
echo "$num1 / $num2 = $quotient (Note: This is Integer Division)"
echo "$num1 % $num2 = $remainder (This is the Remainder)"
fi
echo "------------------------------------"
echo "Calculation complete."
How It Works: A Step-by-Step Breakdown
Let's break down the key concepts in this script.
read -p "..." num1
The-pflag with thereadcommand is a shortcut. It stands for "prompt." It prints the string in quotes and then waits to read the user's input into the specified variable (num1), all in one clean line.sum=$((num1 + num2))
This is the modern, preferred way to perform math in Bash.$((...)): This syntax is called "arithmetic expansion." It tells Bash to treat everything inside the double parentheses as a math problem.- It's much cleaner than the older
exprcommand and handles spaces and operators more intuitively.
product=$((num1 * num2))
A key advantage of$((...))is that you don't need to escape the multiplication symbol (*). In other parts of the shell,*is a wildcard, but inside arithmetic expansion, it's just "multiply."if [ $num2 -eq 0 ]; then ... fi
This is our crucial error-handling block.if [ ... ]: This is a conditional test.$num2 -eq 0: This checks if the value ofnum2is "equal to" 0. For numbers, we use operators like-eq(equal),-ne(not equal),-gt(greater than), and-lt(less than).- If the test is true (
num2is 0), it prints our error message.
else
This block runs only if theiftest was false (meaningnum2is not 0, and it's safe to divide).quotient=$((num1 / num2))
This performs Integer Division. Bash, by default, does not handle decimal numbers (floating points). This means10 / 3will result in3, not3.333.... This is an important concept to remember!remainder=$((num1 % num2))
The%(modulus) operator gives you the remainder of an integer division. For example,10 % 3results in1(because 10 divided by 3 is 3 with a remainder of 1).
How to Run the Script
Ready to try it? Here's how to run it on any Linux or macOS machine.
Step 1: Create the file
Open your terminal and use nano to create a new file:
nano calculator.sh
Step 2: Paste the code
Copy the entire shell script from the first section and paste it into the nano editor.
Step 3: Save and Exit
(In nano: Press Ctrl+O, Enter to save. Press Ctrl+X to exit.)
Step 4: Make the script executable
We must give the file permission to run:
chmod +x calculator.sh
Step 5: Run it!
Now you can run your script:
./calculator.sh
Example Output (Two Tests)
Here are two examples of the script in action.
Test 1: Normal Operation (e.g., 10 and 3)
$ ./calculator.sh
Enter the first number (a): 10
Enter the second number (b): 3
------------------------------------
You entered: a = 10 and b = 3
Calculating...
------------------------------------
10 + 3 = 13
10 - 3 = 7
10 * 3 = 30
10 / 3 = 3 (Note: This is Integer Division)
10 % 3 = 1 (This is the Remainder)
------------------------------------
Calculation complete.
Test 2: Division by Zero (e.g., 10 and 0)
$ ./calculator.sh
Enter the first number (a): 10
Enter the second number (b): 0
------------------------------------
You entered: a = 10 and b = 0
Calculating...
------------------------------------
10 + 0 = 10
10 - 0 = 10
10 * 0 = 0
10 / 0 = Error: Division by zero is not allowed.
10 % 0 = Error: Division by zero is not allowed.
------------------------------------
Calculation complete.
Challenge Yourself: Get Decimal Results
You've now mastered basic arithmetic and error handling in Bash! You might be wondering, "How do I get decimal answers (like 10 / 3 = 3.33)?"
Bash can't do this by itself, but it can call another program that can! The tool for this is bc (Basic Calculator).
Challenge: Try to figure out how to use bc in your script. Here's a hint:
echo "scale=2; 10 / 3" | bc
Happy scripting!


0 Comments