expr  Linux
Overview
The expr
command in Linux is used for expression evaluation. It primarily handles arithmetic, logical, and string operations from the command line or in shell scripts. expr
can be very effective in scenarios where simple calculations, comparisons, or string manipulations are required without launching a full scripting environment.
Syntax
The basic syntax of the expr
command is as follows:
expr EXPRESSION
Where EXPRESSION
can be an arithmetic operation, a comparison, or a string operation. It is important to note that expressions involving operators should have spaces around them to avoid being interpreted as a single string.
Options/Flags
expr
does not have many options, but understanding its basic usage is crucial:
help
: Display a help message and exit.version
: Output version information and exit.
Most of the functionality comes from the types of expressions you can evaluate:
Examples

Arithmetic Operation:
Calculate the sum of two numbers:expr 5 + 3
Outputs:
8

Logical Operations:
Evaluate if one number is greater than another:expr 10 \> 5
Outputs:
1
(true), returns0
if false. 
String Length:
Get the length of a string:expr length "Hello World"
Outputs:
11

Substring Extraction:
Extract substring starting at position 2 of length 5:expr substr "Hello World" 2 5
Outputs:
ello

Using
expr
in Shell Scripts:
Useexpr
in a bash script to calculate values dynamically:#!/bin/bash a=10 b=20 result=$(expr $a + $b) echo $result
This script calculates the sum of
a
andb
and prints30
.
Common Issues
 Syntax Errors: The most common issue is related to not using spaces around operators. Ensure each part of the expression is separated by spaces.
 Handling Nonnumeric Strings: Trying to perform arithmetic on nonnumeric strings returns an error. Make sure all operands are numeric or use string operations.
Integration
expr
is commonly used within shell scripts or in combination with other Unix commands in pipelines. For example, you can use expr
to calculate loop boundaries or to process numeric commandline arguments.
Example:
#!/bin/bash
for i in $(seq 1 $(expr $1  1))
do
echo "Count: $i"
done
This script prints numbers from 1 to one less than the number passed as a commandline argument.
Related Commands
awk
: A powerful text processing tool that can also handle expressions.sed
: Stream editor for filtering and transforming text, which also supports basic math in some implementations.let
: Another shell builtin for arithmetic operations, more straightforward for pure arithmetic compared toexpr
.
For further reading, the official GNU documentation for coreutils
which includes expr
can be found here.