The expr command in Linux: evaluating expressions in the shell

Introduction

In the world of system administration and shell scripting, having tools that allow you to evaluate expressions quickly and reliably is essential. The expr command is one of those classic utilities that has been present on Unix and Linux systems for decades. Although today there are more powerful alternatives such as Bash arithmetic expansion ($(( ))) or bc, expr remains useful in environments where POSIX shell compatibility is required or when working with very simple scripts. This post explains what expr is, how to use it, what types of expressions it can handle, and what its limitations are, all with practical examples you can copy and paste into your terminal.

What is expr?

The expr command evaluates expressions and writes the result to standard output. It was originally designed to work in the Bourne shell and still adheres to the POSIX standard. It can handle integer arithmetic operations, comparisons, logical operations, and some string manipulations. Its syntax is quite direct: you pass the expression as space-separated arguments and it returns the result as text. If the expression is invalid, expr returns an error message and a non-zero exit status.

Basic Syntax

The general form is:

expr EXPRESSION

Each operator and operand must be separated by spaces. For example, to add two numbers you write expr 5 + 3. The supported arithmetic operators are +, -, *, /, and % (modulo). It is important to remember that the asterisk (*) has special meaning to the shell, so it must be escaped or quoted: expr 5 \* 3 or expr 5 '*' 3. Comparison operators include =, !=, <, <=, >, and >=. They return 1 if the condition is true and 0 if false. Logical operators are | (OR) and & (AND), also requiring escaping or quoting.

This post is also available in ESPAÑOL.

Leave a Reply

Your email address will not be published. Required fields are marked *

Esta obra está bajo una Licencia Creative Commons Atribución 4.0 Internacional para Francesc Roig francesc@vivaldi.net .