Before bash scripts natively supported arithmetic expansion (using the $(( ... )) syntax), Linux administrators relied on the expr command to evaluate mathematical equations and manipulate strings. While modern bash scripting has largely made it obsolete for basic addition and subtraction, expr remains a highly useful utility for complex string evaluation, substring extraction, and pattern matching against regular expressions directly from the command line.
Evaluating Mathematical Expressions
The expr command evaluates mathematical expressions and prints the final result to standard output. However, it is notoriously strict about whitespace formatting. You must provide a space between every single number and operator.
expr 10 + 5
This will correctly output 15. If you type expr 10+5 without spaces, the command will simply echo the literal string “10+5” back to you because it interprets it as a single, indivisible word.
Crucial Warning: When performing multiplication, you must “escape” the asterisk (*) using a backslash. If you do not escape it, the bash shell will intercept the asterisk and interpret it as a wildcard (attempting to multiply your numbers by every file in your current directory), resulting in a syntax error.
expr 5 \* 4
Evaluating String Lengths
Beyond math, expr is excellent for string manipulation. If you need a script to verify that a user’s password meets a minimum length requirement, you can use the length operator.
expr length "MySecurePassword123"
This command evaluates the string and outputs 19, representing the total character count.
Extracting Substrings
You can also use expr to chop a specific section out of a larger string using the substr operator. You must provide the original string, the starting position (1-indexed), and the length of the extraction.
expr substr "UbuntuLinux" 1 6
This command starts at the first character (‘U’) and extracts exactly 6 characters, outputting the word Ubuntu. This is highly useful for parsing formatted log files or extracting specific data from a structured ID number.
Pattern Matching
You can use the colon (:) operator to match a string against a basic regular expression. By default, this will output the number of matching characters.
expr "error_log_2023.txt" : '.*\.txt'
This checks if the filename ends in .txt. Because it matches, it outputs 18 (the length of the matching string). If it did not match, it would output 0.