Home > Environment & Utility > expr

expr: Evaluate Expressions

The expr command evaluates various expressions, including integer arithmetic, string manipulation, and logical operations, and returns the result to standard output. It is useful in shell scripting for calculating variable values or implementing conditional logic.

Overview

The expr command is used to perform arithmetic, relational, logical, and string operations. Each argument is treated as a separate token, so spaces are required between operators and operands.

Key Features

  • Arithmetic operations (addition, subtraction, multiplication, division, modulo)
  • String operations (length, substring, index, regular expression matching)
  • Relational operations (equal to, not equal to, greater than, less than)
  • Logical operations (AND, OR)

Main Operators

The expr command uses various operators to evaluate expressions. Each operator must be treated as a separate argument.

Arithmetic Operators

Relational Operators

Logical Operators

String Operators

Generated command:

Try combining the commands.

Description:

`expr` Executes the command.

Combine the above options to virtually execute commands with AI.

Usage Examples

Basic Arithmetic Operation

expr 10 + 5

Adds two numbers.

Multiplication with a Variable

num=20
expr $num \* 3

Performs multiplication using a variable's value. The multiplication operator (*) has a special meaning in the shell and must be escaped.

Getting String Length

expr length "Hello World"

Returns the length of a given string.

Extracting a Substring

expr substr "example" 3 4

Extracts 4 characters from the string 'example' starting at the 3rd position.

Regular Expression Matching and Extraction

expr "filename.tar.gz" : ".*\.\(tar\.gz\)"

Extracts the part of the string that matches the regular expression. Content within parentheses is returned as a submatch.

Logical AND Operation

expr 5 \& 0

Returns the first operand if both operands are non-zero. The ampersand (&) has a special meaning in the shell for background execution and must be escaped.

Tips & Precautions

Points to note and useful tips when using expr.

Key Precautions

  • **Spaces are Mandatory**: Always include spaces between operators and operands.
  • **Escaping**: Characters that have special meaning in the shell (e.g., `*`, `(`, `)`, `&`, `|`, `<`) must be escaped with a backslash (`\`) or enclosed in quotes.
  • **Integer Operations**: `expr` primarily supports integer operations. For floating-point arithmetic, use other tools like `bc`.
  • **Storing Results**: The output of `expr` is sent to standard output. To store the result in a shell variable, use command substitution (e.g., `result=$(expr 10 + 5)` or `result=`expr 10 + 5``).

Same category commands