When you are writing bash scripts in the Linux terminal, you frequently need to perform basic arithmetic—counting loops, calculating file sizes, or adding variables together. While modern bash includes some built-in math capabilities, the traditional and highly reliable way to evaluate mathematical expressions in a shell script is by using the expr (evaluate expression) command. expr takes the arguments you provide, calculates the mathematical result, and prints that result directly to the standard output.
Basic Arithmetic with expr
The expr command can handle addition (+), subtraction (-), multiplication (*), division (/), and modulus/remainder (%). Because expr is a command-line tool, it is absolutely critical that you place spaces between every single number and mathematical operator.
To add two numbers together:
expr 5 + 3
When you press Enter, the terminal will instantly output 8.
To divide numbers (note that expr only performs integer math and will not return decimals/fractions):
expr 10 / 2
The Multiplication Escape Character Trap
Multiplication is the most common pitfall when using the expr command. If you attempt to run expr 5 * 2, the terminal will throw a syntax error. This happens because the asterisk (*) is a special wildcard character in the Linux shell (meaning “all files”). The shell intercepts the asterisk before expr ever sees it.
To fix this, you must “escape” the asterisk by placing a backslash (\) immediately in front of it. This tells the shell to treat the asterisk as a literal multiplication symbol.
expr 5 \* 2
Using expr in Shell Scripts
When you are writing a bash script, you rarely want to print the math result directly to the screen; you usually want to capture the result and store it in a variable. To do this, you wrap the entire expr command in backticks (`) or use the modern $() syntax.
For example, if you have a variable representing a counter and you want to increase it by one:
#!/bin/bash
COUNTER=5
COUNTER=$(expr $COUNTER + 1)
echo "The new count is $COUNTER"
In this script, expr reads the current value of the variable (5), adds 1 to it, and assigns the new result (6) back into the COUNTER variable.