The expr
command in Bash is used to evaluate expressions and perform arithmetic calculations. It can handle integer arithmetic, string operations, and logical comparisons, making it a versatile tool for scripting and command-line operations.
The basic syntax of the expr
command is as follows:
expr [options] [arguments]
+
: Addition operator.-
: Subtraction operator.*
: Multiplication operator (must be escaped as \*
or enclosed in quotes)./
: Division operator.%
: Modulus operator.=
: String comparison operator.!=
: String inequality operator.>
: Greater than comparison.<
: Less than comparison.\
: Escape character for special characters.To perform basic arithmetic operations:
expr 5 + 3
Output: 8
expr 10 - 4
Output: 6
To multiply two numbers, remember to escape the asterisk:
expr 4 \* 7
Output: 28
To divide two numbers:
expr 20 / 4
Output: 5
To find the remainder of a division:
expr 10 % 3
Output: 1
To compare two strings:
expr "hello" = "hello"
Output: 1
(true)
expr "hello" != "world"
Output: 1
(true)
To check if one number is greater than another:
expr 10 \> 5
Output: 1
(true)
*
or use quotes to avoid syntax errors.$(( ))
for arithmetic operations in Bash, as it is often more straightforward and supports more complex expressions.