Skip to content

expr Command in Linux

Summary

The expr command evaluates expressions and prints the result to standard output. It's a versatile tool for performing arithmetic, string manipulation, and logical operations within shell scripts or on the command line.

Introduction

The expr command is a fundamental utility in Linux for performing calculations and evaluations. It's particularly useful in shell scripting for tasks such as incrementing variables, comparing values, and manipulating strings. While more advanced scripting languages offer more sophisticated tools, expr remains a quick and easy way to handle simple operations directly from the command line or within basic scripts. Keep in mind that modern shells often have built-in arithmetic expansion capabilities (e.g., $(()) in Bash), which can sometimes provide a more convenient alternative.

Use case and Examples

Basic Arithmetic

expr 2 + 2
This command adds 2 and 2 and prints the result, 4, to the standard output. Note the spaces around the operator.

Multiplication and Division

expr 10 \* 3
expr 10 / 3
The first command multiplies 10 by 3 and prints 30. The second command divides 10 by 3 and prints 3. Note that multiplication requires escaping the * character.

String Length

expr length "hello"
This command calculates the length of the string "hello" and prints 5.

Substring Extraction

expr substr "hello world" 1 5
This command extracts a substring from "hello world" starting at position 1 (the first character) with a length of 5, resulting in "hello".

String Index

expr index "hello world" wo
This command finds the index of any of the characters in "wo" within the string "hello world", printing the first match which is 7 (the position of 'w').

Integer increment using variable

COUNTER=1
COUNTER=$(expr $COUNTER + 1)
echo $COUNTER
This snippet initializes a variable COUNTER to 1, then increments it using expr. The result (2) is assigned back to COUNTER and then printed.

Commonly used flags

Flag Description Example
(None) The command doesn't use dashes for operation specifications. Operations are specified with keywords or symbols (+, -, *, /, etc.) expr 5 + 3
length STRING Returns the length of STRING. expr length "example"
substr STRING POSITION LENGTH Returns the substring of STRING starting at POSITION (1-indexed) with length LENGTH. expr substr "foobar" 2 3
index STRING CHARSET Returns the index in STRING where any character in CHARSET is found, or 0 if none are found. expr index "test" et


Share on Share on

Comments