548
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
#!/bin/bash
# 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"
Explanation:
- Shebang (#!): The first line specifies the interpreter to use, which is
/bin/bashin this case. - Input: The script prompts the user to enter two numbers using
readand stores them in variablesnum1andnum2. - Calculation: We use the
echocommand to pipe the expression"$num1 + $num2"(numbers in quotes) tobc. This ensures proper handling of spaces and special characters.bcperforms the addition with high precision. The result is captured using command substitution and assigned to the variablesum. - Output: Finally, the script displays the sum using
echo, along with the original numbers for clarity.
Running the Script:
- Save the script as a file, for example,
add_floats.sh. - Make the script executable using
chmod +x add_floats.sh. - Run the script from the command line:
./add_floats.sh.