What is the expr command?

0138

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

  1. Arithmetic Operations: You can perform basic math operations such as addition, subtraction, multiplication, and division.

    • Addition: expr 5 + 3 results in 8.
    • Subtraction: expr 10 - 4 results in 6.
    • Multiplication: Use expr 4 \* 2 (note the backslash to escape the asterisk) to get 8.
    • Division: expr 20 / 4 results in 5.
  2. String Operations: expr can also be used to manipulate strings, such as extracting substrings or finding the length of a string.

  3. Logical Comparisons: You can use expr to compare values, returning 1 for true and 0 for false. For example:

    • expr 5 = 5 returns 1 (true).
    • expr 5 != 3 returns 1 (true).

Important Usage Notes

  • Spaces: Always include spaces around operators. For example, expr 5 + 3 is correct, while expr 5+3 will not work.
  • Integer Only: expr works 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!

0 Comments

no data
Be the first to share your comment!