expr

evaluate arithmetic and string expressions in shell

TLDR

Evaluate arithmetic expression
$ expr [5] + [3]
Multiply (escape the operator)
$ expr [5] \* [3]
String length
$ expr length "[string]"
Substring extraction (1-indexed)
$ expr substr "[string]" [1] [5]
Pattern matching
$ expr "[string]" : '[regex]'
Compare values (escape the operator)
$ expr [10] \> [5]
Find index of first character match
$ expr index "[string]" "[chars]"

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 (same as STRING : REGEX).
|
Logical OR: ARG1 | ARG2 returns ARG1 if non-null and non-zero, else ARG2.
&
Logical AND: ARG1 & ARG2 returns ARG1 if both are non-null and non-zero, else 0.
--help
Display help information.
--version
Display version information.

INSTALL

sudo apt install coreutils
sudo dnf install coreutils
sudo pacman -S coreutils
sudo apk add coreutils
sudo zypper install coreutils
brew install coreutils
nix profile install nixpkgs#coreutils

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)