Doing Math In Bash

5 min read Oct 09, 2024
Doing Math In Bash

Bash, the Bourne Again Shell, is a powerful command-line interpreter used extensively in Linux and macOS systems. While primarily known for its command execution capabilities, Bash can also handle basic mathematical operations. This opens up possibilities for automating calculations, manipulating data, and scripting tasks involving numbers.

Why Do Math in Bash?

You might wonder why bother with math in Bash when programming languages like Python are more suited for complex calculations. The beauty of Bash lies in its integration with the operating system. It allows you to easily incorporate mathematical computations within scripts, analyze data directly from system logs or files, and perform quick calculations on the fly without needing to write a separate program.

Basic Arithmetic Operations

Bash supports the following arithmetic operations:

  • Addition: +
  • Subtraction: -
  • Multiplication: *
  • Division: /
  • Modulo (remainder): %

These operations are performed using the $((...)) or expr command. Let's illustrate with some examples:

Using $((...)):

# Addition
sum=$(( 5 + 3 ))
echo "Sum: $sum"  # Output: Sum: 8

# Subtraction
difference=$(( 10 - 7 ))
echo "Difference: $difference"  # Output: Difference: 3

# Multiplication
product=$(( 4 * 6 ))
echo "Product: $product"  # Output: Product: 24

# Division
quotient=$(( 12 / 3 ))
echo "Quotient: $quotient"  # Output: Quotient: 4

# Modulo
remainder=$(( 17 % 5 ))
echo "Remainder: $remainder"  # Output: Remainder: 2

Using expr:

# Addition
sum=$(expr 5 + 3)
echo "Sum: $sum"  # Output: Sum: 8

# Subtraction
difference=$(expr 10 - 7)
echo "Difference: $difference"  # Output: Difference: 3

# Multiplication
product=$(expr 4 \* 6)
echo "Product: $product"  # Output: Product: 24

# Division
quotient=$(expr 12 / 3)
echo "Quotient: $quotient"  # Output: Quotient: 4

# Modulo
remainder=$(expr 17 % 5)
echo "Remainder: $remainder"  # Output: Remainder: 2

Important Note: When using expr, you need to escape the multiplication operator (*) with a backslash (\).

Handling Variables

You can easily incorporate variables into your calculations. Just remember to use the dollar sign ($) before the variable name to reference its value:

number1=15
number2=8

sum=$(( number1 + number2 ))
echo "Sum: $sum"  # Output: Sum: 23

Working with Floating-Point Numbers

Bash natively supports only integer arithmetic. For calculations involving decimal numbers, you'll need external tools like bc or awk.

Using bc:

# Basic calculation
result=$(echo "1.25 + 3.75" | bc)
echo "Result: $result"  # Output: Result: 5

# Assign variables
num1=2.5
num2=1.5

result=$(echo "$num1 * $num2" | bc)
echo "Result: $result"  # Output: Result: 3.75

Using awk:

# Basic calculation
result=$(awk '{print 1.25 + 3.75}')
echo "Result: $result"  # Output: Result: 5

# Assign variables
num1=2.5
num2=1.5

result=$(awk '{print '$num1' * '$num2'}')
echo "Result: $result"  # Output: Result: 3.75

Advanced Operations and Functions

Bash allows you to define functions for more complex calculations:

# Calculate the area of a rectangle
area_rectangle() {
  length=$1
  width=$2
  area=$(( length * width ))
  echo "Area of rectangle: $area"
}

# Call the function
area_rectangle 10 5  # Output: Area of rectangle: 50

Example: Calculating Disk Usage

Here's a practical example that demonstrates how to calculate disk usage using Bash and df:

# Get disk usage for the root partition
disk_usage=$(df -h / | awk '{print $5}' | sed 's/%//')

# Calculate the percentage of disk space used
used_percentage=$(( disk_usage / 100 * 100 ))

# Display the result
echo "Disk usage: $used_percentage%"

Conclusion

Bash, despite its primary focus on command execution, provides a solid foundation for basic mathematical operations. Whether you're scripting simple calculations or analyzing system data, understanding how to perform math in Bash enhances your command-line proficiency.

Featured Posts