The expr
command is a Linux utility tool used to evaluate and display mathematical expressions. It can perform arithmetic operations such as addition, subtraction, multiplication, division, and modulus. This command is useful for shell scripts that require mathematical calculations.
Overview
The syntax for the expr
command is as follows:
expr ARG1 OPERATOR ARG2
Where ARG1
and ARG2
are the expressions to be evaluated, and OPERATOR
is the arithmetic operator. The result of the expression is then displayed on the standard output.
Examples
Here are some examples of how to use the expr
command:
To add two numbers:
$ expr 10 + 5
15
To subtract two numbers:
$ expr 10 - 5
5
To multiply two numbers:
$ expr 10 \* 5
50
To divide two numbers:
$ expr 10 / 5
2
To get the remainder of a division:
$ expr 10 % 3
1
Specific Use Cases
The expr
command can be used in various scenarios, including:
- To calculate the total size of a directory or file
- To perform calculations within shell scripts
- To perform simple arithmetic operations on command-line arguments
Options
Here is a table of available options for the expr
command:
Option | Description |
---|---|
: |
Assigns the value of the expression to a variable |
length |
Returns the length of the string |
substr |
Returns a substring of a string |
match |
Searches for a regular expression pattern in a string |
index |
Returns the position of a substring in a string |
length |
Returns the length of a string |
+ |
Adds two expressions |
- |
Subtracts two expressions |
* |
Multiplies two expressions |
/ |
Divides two expressions |
% |
Returns the remainder of a division |
Troubleshooting tips
Here are some common issues that you may encounter when using the expr
command, along with their solutions:
Invalid Operator Error
If you receive an “invalid operator” error, make sure that you have specified the correct operator. Check for typos or incorrect syntax.
Division by Zero Error
If you receive a “division by zero” error, make sure that the second argument is not zero. If it is zero, change it to a non-zero value.
Syntax Error
If you receive a syntax error, make sure that you have correctly specified the arguments and operators. Check for typos or incorrect syntax.
Notes
- The
expr
command can only perform integer arithmetic. It cannot handle floating-point numbers. - When using the multiplication operator
*
, you must escape it with a backslash (\
) or enclose the expression in quotes to prevent shell expansion.