Bash Script to Multiply Two Numbers with Output
Use arithmetic expansion in Bash like
result=$((num1 * num2)) to multiply two numbers and then print the result with echo.Examples
Input3 and 4
Output12
Input0 and 5
Output0
Input-2 and 6
Output-12
How to Think About It
To multiply two numbers in Bash, you take the two inputs and use the arithmetic expansion syntax
$(( )) with the multiplication operator *. This calculates the product and stores it in a variable, which you then print.Algorithm
1
Get the first number as input2
Get the second number as input3
Multiply the two numbers using arithmetic expansion4
Store the result in a variable5
Print the resultCode
bash
#!/bin/bash read -p "Enter first number: " num1 read -p "Enter second number: " num2 result=$((num1 * num2)) echo "The product is: $result"
Output
Enter first number: 3
Enter second number: 4
The product is: 12
Dry Run
Let's trace multiplying 3 and 4 through the code
1
Input first number
num1 = 3
2
Input second number
num2 = 4
3
Calculate product
result = 3 * 4 = 12
4
Print result
Output: The product is: 12
| Step | Variable | Value |
|---|---|---|
| 1 | num1 | 3 |
| 2 | num2 | 4 |
| 3 | result | 12 |
Why This Works
Step 1: Reading inputs
The script uses read to get two numbers from the user and stores them in variables.
Step 2: Multiplying numbers
It uses Bash arithmetic expansion $(( )) with the * operator to multiply the two numbers.
Step 3: Displaying result
The product is stored in a variable and printed with echo to show the output.
Alternative Approaches
Using expr command
bash
#!/bin/bash read -p "Enter first number: " num1 read -p "Enter second number: " num2 result=$(expr $num1 \* $num2) echo "The product is: $result"
Uses external command expr; less efficient but works in older shells.
Using let command
bash
#!/bin/bash read -p "Enter first number: " num1 read -p "Enter second number: " num2 let result=num1*num2 echo "The product is: $result"
Uses built-in let for arithmetic; simpler but less flexible than $(( )).
Complexity: O(1) time, O(1) space
Time Complexity
Multiplying two numbers is a single arithmetic operation, so it runs in constant time.
Space Complexity
Only a few variables are used to store inputs and output, so space is constant.
Which Approach is Fastest?
Using Bash arithmetic expansion $(( )) is fastest because it is built-in, while expr calls an external program.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Arithmetic Expansion $(( )) | O(1) | O(1) | Fast, modern Bash scripts |
| expr command | O(1) | O(1) | Compatibility with older shells |
| let command | O(1) | O(1) | Simple arithmetic in Bash |
Always use
$(( )) for arithmetic in Bash for clarity and speed.Forgetting to use
$(( )) causes the script to treat multiplication as a string, not math.