What is the 'expr' command?

096

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

  1. Arithmetic Operations: You can perform addition, subtraction, multiplication, division, and modulus. For example:

    expr 5 + 3   # Adds 5 and 3, output: 8
    expr 10 - 2  # Subtracts 2 from 10, output: 8
    expr 4 \* 2  # Multiplies 4 by 2, output: 8 (note the escape character for *)
    expr 16 / 4  # Divides 16 by 4, output: 4
  2. String Operations: It can also be used to concatenate strings:

    expr "Hello, " : '.*'  # Outputs the length of the string "Hello, "
  3. Logical Comparisons: You can compare integers:

    expr 5 = 5   # Checks if 5 is equal to 5, output: 1 (true)
    expr 5 != 3  # Checks if 5 is not equal to 3, output: 1 (true)

Important Notes

  • Spaces: Always include spaces around operators; for example, use expr 5 + 3 instead of expr 5+3.
  • Escape Characters: For multiplication, use a backslash (\) before the asterisk (*) to prevent the shell from interpreting it as a wildcard.

Example Usage

Here’s a simple example of using expr in a terminal session:

# 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 straightforward way to perform calculations directly in the terminal, making it a useful tool for quick arithmetic without needing a separate calculator application. If you're interested in more advanced calculations or scripting, consider exploring other command-line tools or programming languages like Python or Bash scripting.

Feel free to ask if you have more questions or need further examples!

0 Comments

no data
Be the first to share your comment!