162
Shell scripts are a great way to automate tasks on your computer. One basic function they can perform is simple arithmetic. In this post, we’ll create a shell script to add two numbers.
Here’s what we’ll do
- Prompt the user for input: The script will ask the user to enter two numbers.
- Store the input: We will use the
read
command to store these values in variables. - Perform the addition: The script will use either the
expr
command or arithmetic expansion to add the two numbers. - Display the result: Finally, we will use the
echo
command to display the sum on the screen.
#!/bin/bash
echo "Enter the first number: "
read first_num
echo "Enter the second number: "
read second_num
# Using expr (for compatibility with older shells)
# sum=$(expr $first_num + $second_num)
# Using arithmetic expansion (for modern shells)
sum=$((first_num + second_num))
echo "The sum of $first_num and $second_num is: $sum"
Explanation
- The first line
#!/bin/bash
tells the system which interpreter to use to run the script (in this case, bash). - The
echo
commands display prompts for the user to enter the numbers. - The
read
command stores the user’s input in the variablesfirst_num
andsecond_num
. - We commented out the
expr
method for demonstration purposes. It’s a common way to perform arithmetic in older shells but may not be available on all systems. - The uncommented line uses arithmetic expansion, a feature available in most modern shells. It allows for performing calculations directly within double parentheses
(( ))
. - The final
echo
command displays the result, including the stored variable values.
Saving and Running the Script
- Save the script as a file with a
.sh
extension (e.g.,add_numbers.sh
). - Open a terminal window and navigate to the directory where you saved the script.
- Make the script executable using the
chmod +x add_numbers.sh
command. - Run the script using
./add_numbers.sh
.