Home Linux Shell Script to Add Two Float Numbers

Shell Script to Add Two Float Numbers

by Anup Maurya
9 minutes read

In this article, we will explore the use of floating-point numbers in shell scripting and we’ll create a shell script to Add Two Float Numbers.

In shell scripting, floating point numbers are decimal numbers used to represent real numbers with a fractional part. They are represented as double-precision numbers and are stored as 64-bit values in memory.

Shell Script to Add Two Float Numbers


# Prompt the user for two numbers
echo "Enter the first number: "
read num1

echo "Enter the second number: "
read num2

# Use bc for accurate floating-point addition
sum=$(echo "$num1 + $num2" | bc)

# Display the sum
echo "The sum of $num1 and $num2 is: $sum"


  1. Shebang (#!): The first line specifies the interpreter to use, which is /bin/bash in this case.
  2. Input: The script prompts the user to enter two numbers using read and stores them in variables num1 and num2.
  3. Calculation: We use the echo command to pipe the expression "$num1 + $num2" (numbers in quotes) to bc. This ensures proper handling of spaces and special characters. bc performs the addition with high precision. The result is captured using command substitution and assigned to the variable sum.
  4. Output: Finally, the script displays the sum using echo, along with the original numbers for clarity.

Running the Script:

  1. Save the script as a file, for example, add_floats.sh.
  2. Make the script executable using chmod +x add_floats.sh.
  3. Run the script from the command line: ./add_floats.sh.

related posts

Leave a Comment