Session and utilities

The expr command

Evaluates arithmetic, string and logical expressions from the command line and writes the result to the output. Older scripts used it to count and compare.

Syntax

expr expresiónTry it in the terminal →

Most useful options

+ - * / %Integer arithmetic. The asterisk must be escaped in the shell
< <= = != >= >Comparisons: they return 1 if true and 0 if false
| &Logical: | returns the first value that is neither null nor zero; & returns the first if neither is null or zero, otherwise 0
length, substr, indexText: length counts characters; substr cuts from a position; index finds the first position of a character
CADENA : REGEXMatches a regular expression from the start; returns the part captured in escaped parentheses, or the number of characters

Copy-ready examples

$ expr 7 + 5integer addition; the result goes to the standard output.

Example output

12
$ expr 7 \* 6multiplication with the escaped asterisk. Prints 42.

Example output

42
$ expr 10 % 3remainder of the division: prints 1.

Example output

1
$ expr length "hola mundo"counts the characters of a text, spaces included.

Example output

10
$ expr substr hola 2 3cuts three characters starting at position 2: prints ola.

Example output

ola

You can try them in the browser terminal: it does not touch your computer.

Common errors

MessageCauseFix
expr: division by zeroYou divided by zero, for example expr 5 / 0. It is a calculation error, not a syntax one.Check that the divisor is not 0 before calculating, for example with if.
expr: non-integer argumentexpr only calculates with integers, and one of the operands is not one, or it is empty.Use $(( )) or bc if you need decimals, and check that the variables have a value.
expr: syntax error: unexpected argument '5'An operator is missing between the numbers: expr 5 5 does not know what to do with the second one.Check the expression and put an operator between each pair of operands.

Typical mistakes

  • expr only works with integers: 7 / 2 gives 3, not 3.5.
  • A result of 0 or empty makes expr exit with status 1, even though it printed 0. set -e and if read that as a failure.
  • Without escaping the asterisk, the shell replaces it with the file names in the folder before expr sees it.

Differences from similar commands

  • bc: arbitrary-precision calculator, with decimals. expr only does integers.
  • seq: generates sequences of numbers; expr calculates with the numbers you already have.
  • $(( )): shell arithmetic, the modern alternative: faster and with no escaping.

Related commands

FAQ

How do I use expr in a loop?

With i=$(expr $i + 1). In bash, $((i + 1)) is faster and needs no escaping.

Can expr extract part of a text?

Yes: substr, length, index, and the : operator with parentheses to capture. For complex text, sed or cut are clearer.

Learn to actually use it

The basic Linux course takes you from zero to console fluency with 24 self-grading lessons.

Start the free course