Arithmetic Expressions In Bash – Using (( And $(( For Math

Performing Math in Bash Shell Scripts

Bash provides built-in support for integer arithmetic operations through two main constructs – double parentheses (( )) and dollar-double parentheses $(( )) expressions. Both allow performing common math calculations directly inside Bash scripts and at the command line interface.

Arithmetic expressions enable substitution of numeric variables and calculations into strings for printing and command execution and can greatly simplify math-heavy workflows and scripting. Understanding the precise differenes and appropriate use cases of (( )) and $(( )) can enable more efficient and cleaner bash coding.

Using Double Parentheses for Arithmetic Evaluation

Double parentheses (( )) provide a method to evaluate integer arithmetic expressions directly in Bash. They act similarly to an arithmetic evaluation function taking an equation as its argument but without requiring a leading dollar sign ($).

Overview of (( for math operations without $

The (( )) construct performs arithmetic expansion and evaluates enclosed expressions as arithmetic formulas. Unlike $(( )) which outputs results as strings, (( ))instead returns exit codes to signify whether evaluation succeeded.

This allows using (( )) for arithmetic comparisons in conditional expressions like if statements where the exit code determines control flow. Exit code 0 indicates true, while 1 signals false. Any non-zero return exits the current shell.

Examples of arithmetic expressions with (( ))

Here are some examples of math operations inside double parenthesis (( )):

(( 2 + 5 ))      # Simple addition
(( var1 = 10 ))  # Variable assignment 
(( var2++ ))     # Increment variable
(( var1 > 7 ))   # Numerical comparison
(( var1 -= 3 ))  # Subtract and assign

As shown above, (( )) allows setting variables, incrementing values with ++, comparisons like > and >=, and compound assign-and-calculate operators +=, -=, *= all without needing $ or expr. Flow control statements can test the exit code:

(( var1 > 10 ))
if [ $? -eq 0 ]; then
  echo "var1 is greater than 10"
fi

Explanation of return values and exit statuses

Rather than expanding to a output string, (( )) instead returns an exit status like other Bash builtin functions:

  • Exit code 0 – Indicates successful evaluation and arithmetic true
  • Exit code 1 – Denotes arithmetic false, similar to a failed comparison
  • Non-zero exit code – Forwards an error exit status, terminating current shell process

This makes (( )) expressions work for conditional tests like if statements. The $? variable gives the most recent exit code:

  
(( var1 == 10 ))
echo $? # Prints 0 (true) or 1 (false) 

Keep this distinction in mind between string-output $(( )) and exit code-based (( )) when choosing which to use.

Embedding Expressions with $(( ))

Whereas (( )) is best for comparisons and tests, the $(( )) construct instead allows math expressions to be embedded inline within strings and expanded to numeric values.

Purpose and syntax of $(( )) for math in strings

$(( )) substitutes the result of an enclosed arithmetic expression into the surrounding string. This works because Bash performs the math first then inserts the calculated value.

The syntax mirrors (( )) but with a leading $ to denote a string rather than just exit code:

    
var="The result is $(( 2 + 4 ))"
# var = "The result is 6"

Anything between $(( and )) gets evaluated mathematically. This substring expansion makes it easy to inline math directly inside strings and commands.

Substituting calculated values into variables

A common use case for $(( )) is assigning calculated values to variables. Just enclose the equation in $(( )) when setting the variable:

value=$(( 20 + 5 )) # value = 25
width=$((12 / 3)) # width = 4 

Bash replaces $(( equation )) with the solved math before assigning to the variable. This evaluates the expression at time of assignment rather than each future reference. Enables separating complex formulas from usage.

Concatenating equations inline in commands

Since $(( )) embeds the math result into a string, it can be combined directly inside commands:

echo "5 + 3 is equal to $(( 5 + 3 ))"
# Prints "5 + 3 is equal to 8"

This concatenation eliminates the need for intermediate variables when inserting simple math into strings.

Comparisons and Best Practices

To recap, (( )) and $(( )) provide related but distinct math evaluation functions:

  • (( )) – Encloses arithmetic expressions to evaluate as exit code status
  • $(( )) – Embeds solved math equation into surrounding string

Comparing (( )) and $(( )) for speed and use cases

In terms of speed, $(( )) generally executes faster since it only cares about the result value. There is no need to set exit codes and related status tracking.

However for math comparisons in if statements and loops, (( )) is required since the exit status determines whether the condition passed. $(( )) alone would always substitute a set value.

In summary:

  • Use (( )) for: Testing variables and math comparisons
  • Use $(( )) for: Embedding calculated values in strings

Recommendations for arithmetic in scripts

Here are some best practices when leveraging arithmetic evaluation in bash scripts:

  • Use $(()) over legacy backtick `expr` – More concise and readable
  • For complex formulas, assign to variables first
  • When possible, initialize totals outside loops then accumulate
  • Prefer (( )) over external expr command – Runs faster internally
  • Enclose variables in math expressions to avoid string concatenation

Both types of arithmetic expansion allow cleaner scripts versus old-style expr, awk, cut, sed, perl, or external tools. Keep $(( )) and (( )) in mind as alternatives for inline math instead of subshells or external commands.

Leave a Reply

Your email address will not be published. Required fields are marked *