What is bash arithmetic syntax?

QuestionsQuestions8 SkillsProDec, 25 2025
0100

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, so 5/2 equals 2)
  • % : Modulo (returns the remainder, e.g., 5%2 is 1)

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:

  1. It is faster.
  2. It handles spaces more easily.
  3. 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?

0 Comments

no data
Be the first to share your comment!