In Bash, floating-point arithmetic is not directly supported using standard arithmetic operators. However, you can use the bc command, which is a calculator language that supports floating-point operations. Here's how you can handle floating-point arithmetic in Bash:
Example of Floating-Point Arithmetic in Bash
#!/bin/bash
# Define floating-point numbers
num1=10.50
num2=3.20
# Perform arithmetic using bc
sum=$(echo "$num1 + $num2" | bc)
difference=$(echo "$num1 - $num2" | bc)
product=$(echo "$num1 * $num2" | bc)
quotient=$(echo "scale=2; $num1 / $num2" | bc) # scale=2 for 2 decimal places
# Print the results
echo "Addition: $num1 + $num2 = $sum"
echo "Subtraction: $num1 - $num2 = $difference"
echo "Multiplication: $num1 * $num2 = $product"
echo "Division: $num1 / $num2 = $quotient"
Explanation
- The
echocommand sends the arithmetic expression tobc. - The
scalevariable inbcspecifies the number of decimal places to include in the result. - The results are captured in variables and printed using
echo.
Running the Script
Make the script executable and run it:
chmod +x script.sh
./script.sh
This will perform the floating-point arithmetic and display the results.
