Back to the command reference

expr

ShellAdvanced In simulator In real Linux

Evaluate expressions

Name: expr = expression

You can practise it right away in the simulator, and use it in real Linux mode too.

Description

expr evaluates integer arithmetic, comparisons and string expressions and prints the result. Every operator and operand must be a separate argument, and * must be escaped. It is how early shells did arithmetic; $(( )) is used today.

Syntax

expr EXPRESSION

Common options

+ - \* / %Integer arithmetic (escape the *)
= / != / < / >Compare: 1 (true) or 0 (false); escape < and >
lengthString length
substr / indexSubstring: expr substr "hello" 2 3 → ell; index finds a character
:Regular expression match: expr "$s" : '[0-9]*' gives the length of the leading digits

Examples

  • $ expr 3 + 4

    Prints 7

    Explain
  • $ expr length "hello"

    Prints 5

    Explain
  • $ echo $((3 * 4))

    Nowadays $(( )) is more common

    Explain

Related