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.
The syntax for the
expr command is as follows:
expr ARG1 OPERATOR ARG2
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.
Here are some examples of how to use the
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
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
Here is a table of available options for the
||Assigns the value of the expression to a variable|
||Returns the length of the string|
||Returns a substring of a string|
||Searches for a regular expression pattern in a string|
||Returns the position of a substring in a string|
||Returns the length of a string|
||Adds two expressions|
||Subtracts two expressions|
||Multiplies two expressions|
||Divides two expressions|
||Returns the remainder of a division|
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.
If you receive a syntax error, make sure that you have correctly specified the arguments and operators. Check for typos or incorrect syntax.
exprcommand 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.