0
0
Bash-scriptingHow-ToBeginner · 3 min read

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+4 is wrong, use expr 3 + 4).
  • For multiplication, forgetting to escape the * (use \*).
  • Using expr for 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

OperatorDescriptionExampleOutput
+Additionexpr 4 + 59
-Subtractionexpr 10 - 37
\*Multiplication (escape *)expr 6 \* 742
/Divisionexpr 20 / 45
%Moduloexpr 10 % 31
>Greater than (returns 1 if true)expr 5 \> 31
<Less than (returns 1 if true)expr 2 \< 41
=Equal (returns 1 if true)expr 3 = 31

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.