In Bash, there are a few ways to perform math, but the most common and recommended syntax—which you will use in this lab—is Double Parentheses (( )).
Here is a breakdown of the syntax:
1. The Basic Syntax: $(( expression ))
To calculate a value and use the result, you wrap the math expression in $(( )).
# Example: Adding two numbers
sum=$((5 + 3))
echo $sum # This will print 8
2. Common Operators
Bash supports standard mathematical operators:
+: Addition-: Subtraction*: Multiplication/: Division (Note: Bash does integer division, so5/2equals2)%: Modulo (returns the remainder, e.g.,5%2is1)
3. Using Variables in Math
One of the coolest features of the $(( )) syntax is that you don't strictly need the $ sign for variables inside the parentheses (though you can use it).
apples=10
oranges=5
# Both of these work:
total=$((apples + oranges))
total=$(($apples + $oranges))
4. Why use this instead of other methods?
You might see older scripts using the expr command or let, but $(( )) is the modern standard because:
- It is faster.
- It handles spaces more easily.
- It is much easier to read.
In your fruit_basket.sh script, you'll be using this syntax to manage your fruit inventory! Does that make sense, or would you like to see an example of subtraction or multiplication?