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:
Syntax
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
#!/bin/bash
result=$(expr 5 + 3)
echo "5 + 3 = $result"
result=$(expr 10 \* 2)
echo "10 * 2 = $result"
Login to try C/C++/Java/PHP code in the editor
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
- Forgetting spaces around operators, as in
expr 1+2, which prints1+2as text. - Using
*unescaped, as inexpr 2 * 3, which the shell expands as a file wildcard; write\*. - Expecting
exprto do decimals, when it works only with integers.
🔒
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: