expr

expr evaluates a single expression and prints its value.

expr expression
$ expr 6 + 7
13
$ expr length "Peios"
5

Each part of the expression — every number, operator, and keyword — is a separate argument. That is why the spaces matter: expr 6+7 is one argument and not an expression, while expr 6 + 7 is three.

Arithmetic #

OperatorResult
ARG1 + ARG2Sum.
ARG1 - ARG2Difference.
ARG1 * ARG2Product.
ARG1 / ARG2Integer quotient.
ARG1 % ARG2Remainder.

Comparison #

A comparison yields 1 for true and 0 for false. It is arithmetic when both sides are numbers, and lexical otherwise.

OperatorTrue when…
ARG1 = ARG2the two are equal.
ARG1 != ARG2they are unequal.
ARG1 < ARG2ARG1 is less.
ARG1 <= ARG2ARG1 is less or equal.
ARG1 > ARG2ARG1 is greater.
ARG1 >= ARG2ARG1 is greater or equal.

Logic #

OperatorResult
ARG1 | ARG2ARG1 if it is neither null nor 0; otherwise ARG2.
ARG1 & ARG2ARG1 if neither argument is null or 0; otherwise 0.

String operations #

FormResult
length STRINGThe number of characters in STRING.
substr STRING POS LENGTHLENGTH characters of STRING, counting POS from 1.
index STRING CHARSThe position of the first of any of CHARS in STRING, or 0.
STRING : REGEXPMatch REGEXP anchored at the start of STRING. Returns the matched length, or the text captured by \(…\).
match STRING REGEXPThe same as STRING : REGEXP.

Many of these operators — *, <, |, ( — are also meaningful to a shell, so quote or escape them so they reach expr intact.

Exit status #

expr's exit status reports on the value it computed:

CodeMeaning
0The result was neither null nor 0.
1The result was null or 0.
2The expression was syntactically invalid.
3An error occurred during evaluation — such as division by zero.

Edit this page