Home Linux Shell Script to Add Two Numbers

Shell Script to Add Two Numbers

by Anup Maurya
9 minutes read

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

  1. Prompt the user for input: The script will ask the user to enter two numbers.
  2. Store the input: We will use the read command to store these values in variables.
  3. Perform the addition: The script will use either the expr command or arithmetic expansion to add the two numbers.
  4. 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 variables first_num and second_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

  1. Save the script as a file with a .sh extension (e.g., add_numbers.sh).
  2. Open a terminal window and navigate to the directory where you saved the script.
  3. Make the script executable using the chmod +x add_numbers.sh command.
  4. Run the script using ./add_numbers.sh.

related posts

Leave a Comment

Enable Notifications OK No thanks