Ever needed a quick way to multiply two numbers on your Linux or Unix system? A shell script can be a handy tool for this task. In this post, we’ll create a shell script to Multiply Two Numbers
Method 1: Using Arithmetic Expansion (Bash)
This method is the most concise and modern way to perform arithmetic operations within the shell script itself.
#!/bin/bash
# Prompt the user for two numbers
read -p "Enter the first number: " num1
read -p "Enter the second number: " num2
# Perform multiplication using arithmetic expansion
product=$((num1 * num2))
# Display the result
echo "The product of $num1 and $num2 is: $product"Explanation:
#!/bin/bashspecifies the interpreter for the script (Bash in this case).readcommands prompt the user for input and store them in variablesnum1andnum2.(( ))performs arithmetic expansion. Here,num1 * num2multiplies the two numbers and assigns the result toproduct.echodisplays the final message with the calculated product.
Method 2: Using expr command
This method utilizes the expr command for performing calculations.
#!/bin/bash
# Prompt the user for two numbers
read -p "Enter the first number: " num1
read -p "Enter the second number: " num2
# Perform multiplication using expr
product=`expr $num1 \* $num2` # Escape the asterisk for multiplication
# Display the result
echo "The product of $num1 and $num2 is: $product"
Explanation:
- Similar to the first method for prompting for input.
exprcommand is used for arithmetic operations. Here,$num1 \* $num2performs the multiplication with escaping the asterisk (*) to avoid conflicts with filename globbing.- The result is stored in the
productvariable using backticks. echodisplays the final message.
Saving and Running the Script
- Save the script as a file with a
.shextension (e.g.,multiply.sh). - Make the script executable using
chmod +x multiply.sh. - Run the script from your terminal:
./multiply.sh.
These scripts provide a basic way to multiply two numbers using shell scripting. You can modify them further to accept arguments from the command line or perform more complex calculations.