How to Use expr in Bash: Syntax and Examples
In bash,
expr is a command used to evaluate expressions like arithmetic calculations and string operations. You write expressions as arguments to expr, and it outputs the result. For example, expr 3 + 4 outputs 7.Syntax
The basic syntax of expr is:
expr expression
Where expression can be arithmetic (like addition, subtraction), string operations, or comparisons.
Important parts:
- Operators like
+,-,*,/,%for math. - Spaces are required between operands and operators.
- Use backslash
\to escape special characters like*.
bash
expr 5 + 3 expr 10 \* 2 expr 15 / 3
Output
8
20
5
Example
This example shows how to add two numbers and compare them using expr:
bash
#!/bin/bash num1=7 num2=5 sum=$(expr $num1 + $num2) echo "Sum: $sum" comparison=$(expr $num1 \> $num2) echo "Is num1 greater than num2? $comparison"
Output
Sum: 12
Is num1 greater than num2? 1
Common Pitfalls
Common mistakes when using expr include:
- Not putting spaces around operators (e.g.,
expr 3+4is wrong, useexpr 3 + 4). - For multiplication, forgetting to escape the
*(use\*). - Using
exprfor floating-point math (it only supports integers). - Not quoting variables that might be empty, which can cause errors.
Example of wrong and right usage:
bash
expr 3+4 expr 3 + 4 expr 5 * 2 expr 5 \* 2
Output
expr: syntax error
7
expr: syntax error
10
Quick Reference
| Operator | Description | Example | Output |
|---|---|---|---|
| + | Addition | expr 4 + 5 | 9 |
| - | Subtraction | expr 10 - 3 | 7 |
| \* | Multiplication (escape *) | expr 6 \* 7 | 42 |
| / | Division | expr 20 / 4 | 5 |
| % | Modulo | expr 10 % 3 | 1 |
| > | Greater than (returns 1 if true) | expr 5 \> 3 | 1 |
| < | Less than (returns 1 if true) | expr 2 \< 4 | 1 |
| = | Equal (returns 1 if true) | expr 3 = 3 | 1 |
Key Takeaways
Always put spaces around operators when using expr.
Escape special characters like * with a backslash (\*).
expr only supports integer arithmetic, not floating-point.
Use expr for simple math and string comparisons in bash scripts.
Quote variables in expr to avoid errors if they are empty.