expr

NAME

expr - simple expression evaluator

SYNOPSIS

expr expression

DESCRIPTION

The expr(1) utility parses an expression provided as arguments and prints the result on the standard output.

The expr(1) utility recognizes three types of operators: relational operators, arithmetic operators and string operators. The following left-associative binary operators are listed from lowest to highest precedence:

expr | expr
Yields the first expr if it is neither null nor 0; otherwise, it yields the second expr.
expr & expr
Yields the first expr if neither expr is null or 0; otherwise, it yields 0.
expr relop expr
Where relop is one of <, <=, =, !=, >=, or >, yields 1 if the indicated comparison is true; it yields 0 if false. The comparison is numeric if the two expressions are integers; otherwise, it is lexicographic.
expr + expr
expr - expr
Addition or subtraction of the arguments.
expr * expr
expr / expr
expr % expr
Multiplication, division, or remainder of the arguments.
expr : expr
The matching operator compares the string first argument with the regular expression second argument; regular expression matching is the same as the ed(1) editor. The \( \) pattern symbols can be used to select a portion of the first argument. Otherwise, the matching operator yields the number of characters matched (0 on failure).
( expr)
Parentheses for grouping expressions.

DIAGNOSTICS

The expr(1) utility exits with 0 if the expression is neither null nor 0, exits with 1 if the expression is null or 0, and exits >1 if there is an error in the expression.

EXAMPLES

A simple arithmetic calculation; the answer is 8, because division is performed first.

$ expr 4 + 8 / 2
8

Check to see if the value of variable input is hello:

$ expr "$input" = "hello"

List the number of characters in the first directory in your PATH:

$ expr 'echo $PATH' : \[^:]*

Extract the first directory in your PATH; both characters in \( need to be escaped for the shell. An alternate form using single quotes instead of backslashes is also shown:

$ expr "$(echo $PATH)" : \\\(\[^:]*\\\):.*
$ expr "$(echo $PATH)" : '\(\[^:]*\):.*'
When matching strings, expr(1) is best for breaking a string into two parts; it is not very useful for extracting a particular word.

NOTES

Many of the operators are special to the shell and must be quoted.

Operators cannot be used as (string) operands.

SEE ALSO

sh(1)

test(1)