The expr command is a utility in Unix and Linux systems used for evaluating expressions and performing basic arithmetic operations. It can handle integer arithmetic, string operations, and logical comparisons.
Key Features of expr
-
Arithmetic Operations: You can perform basic math operations such as addition, subtraction, multiplication, and division.
- Addition:
expr 5 + 3results in8. - Subtraction:
expr 10 - 4results in6. - Multiplication: Use
expr 4 \* 2(note the backslash to escape the asterisk) to get8. - Division:
expr 20 / 4results in5.
- Addition:
-
String Operations:
exprcan also be used to manipulate strings, such as extracting substrings or finding the length of a string. -
Logical Comparisons: You can use
exprto compare values, returning1for true and0for false. For example:expr 5 = 5returns1(true).expr 5 != 3returns1(true).
Important Usage Notes
- Spaces: Always include spaces around operators. For example,
expr 5 + 3is correct, whileexpr 5+3will not work. - Integer Only:
exprworks with integers only; it does not handle floating-point arithmetic.
Example Usage
Here’s a simple example of using expr in the terminal:
# Calculate the sum of two numbers
result=$(expr 10 + 5)
echo "The result is: $result" # Outputs: The result is: 15
Conclusion
The expr command is a powerful tool for quick calculations and evaluations directly in the terminal, making it a valuable asset for scripting and command line operations. If you're looking to enhance your command line skills, practicing with expr can be a great start!
