← Back to Bash Course | Chapter 4: Loops | Lesson 1 of 14

expr

expr is like an old pocket calculator that needs each number and sign to be set apart with spaces before it will give you the answer.

In this page:

  1. expr
Syntax
bash
result=$(expr operand1 operator operand2)

expr

expr is an older external command that evaluates a simple arithmetic or string expression and prints the result. It requires spaces around every operator and operand, unlike $(( )).

Most modern scripts prefer $(( )) or let, but expr still appears in older scripts.

Warning: expr 1+1 (no spaces) prints 1+1 literally instead of 2 — spaces around operators are mandatory.

Example: expr

bash
#!/bin/bash
result=$(expr 5 + 3)
echo "5 + 3 = $result"

result=$(expr 10 \* 2)
echo "10 * 2 = $result"
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting spaces around operators, as in expr 1+2, which prints 1+2 as text.
  2. Using * unescaped, as in expr 2 * 3, which the shell expands as a file wildcard; write \*.
  3. Expecting expr to do decimals, when it works only with integers.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.