When to use (( )) over expr?

QuestionsQuestions8 SkillsProDec, 25 2025
092

In modern shell scripting, you should almost always use (( )) (or $(( ))) instead of expr.

Here is why (( )) is the preferred choice:

1. Readability and Syntax

  • (( )): Is much cleaner. You can use spaces naturally, and you don't need to escape characters.
  • expr: Is clunky. You often have to "escape" characters like the multiplication sign (\*) because the shell would otherwise interpret it as a wildcard (like "all files").

Example Comparison:

# Using (( )) - Simple and clean
result=$(( (5 + 3) * 2 ))

# Using expr - Messy and requires escaping
result=$(expr \( 5 + 3 \) \* 2)

2. Performance

  • (( )): Is a built-in feature of the Bash shell. The shell performs the calculation directly.
  • expr: Is an external program. Every time you use expr, Bash has to create a new process to run that program, which is significantly slower if you are doing many calculations in a loop.

3. Variable Handling

Inside (( )), you don't even need the $ sign to reference variables, making expressions look more like standard algebra:

apples=5
total=$((apples + 10))  # Works perfectly

When would you ever use expr?

The only time you would use expr today is if you are writing a script for a very old system that uses the original Bourne Shell (sh) instead of Bash, as (( )) is a "bashism" (a feature specific to Bash and similar modern shells).

Summary for this Lab:
Since you are using #!/bin/bash at the start of your fruit_basket.sh script, stick with (( )). It is faster, more powerful, and much easier to write

0 Comments

no data
Be the first to share your comment!