LinuxCommandLibrary

expr

TLDR

Evaluate arithmetic expression

$ expr [5] + [3]
copy
String length
$ expr length "[string]"
copy
Substring extraction
$ expr substr "[string]" [1] [5]
copy
Pattern matching
$ expr "[string]" : '[regex]'
copy
Compare values
$ expr [10] \> [5]
copy

SYNOPSIS

expr expression

DESCRIPTION

expr evaluates expressions and outputs the result. It handles integer arithmetic, string operations, and comparisons. Results are printed to standard output with exit status indicating boolean results.
Operators must be passed as separate arguments, with shell metacharacters escaped. For arithmetic, expr only handles integers. String operations include length, substring extraction, and regex matching.
expr is often used in shell scripts for calculations and string manipulation, though modern shells provide built-in alternatives.

PARAMETERS

EXPRESSION

Mathematical or string expression to evaluate.
+, -, \*, /, %
Arithmetic operators (multiply must be escaped).
=, !=, \<, \>, \<=, \>=
Comparison operators (escape < and >).
length STRING
Return string length.
substr STRING POS LEN
Extract substring (1-indexed).
index STRING CHARS
Find first occurrence of characters.
match STRING REGEX
Pattern match and extract.
--help
Display help information.

CAVEATS

Operators need escaping (\* for multiply, \> for comparison). Only integer arithmetic supported. Returns exit code 1 for zero/false results. Regex uses basic regular expressions only.

HISTORY

expr originated in Version 7 Unix (1979) as a general-purpose expression evaluator. It remains part of POSIX and GNU coreutils, though many of its functions are now handled by shell builtins.

SEE ALSO

bc(1), test(1), bash(1)

Copied to clipboard