How do I use expr for calculations?

090

To use expr for calculations in the command line, follow these steps:

Basic Syntax:

expr <expression>

Key Points:

  1. Spaces: Ensure there are spaces around operators (e.g., +, -, *, /).
  2. Operators:
    • Addition: +
    • Subtraction: -
    • Multiplication: * (use \* to escape it)
    • Division: /
    • Modulus: %

Examples:

  1. Addition:

    expr 5 + 3

    Output: 8

  2. Subtraction:

    expr 10 - 4

    Output: 6

  3. Multiplication:

    expr 6 \* 7

    Output: 42

  4. Division:

    expr 20 / 4

    Output: 5

  5. Modulus:

    expr 10 % 3

    Output: 1

Using Variables:

You can also use variables with expr:

a=5
b=3
expr $a + $b

Output: 8

Note:

expr is useful for simple calculations, but for more complex arithmetic, consider using bc or arithmetic expansion $((...)).

Feel free to explore more about these commands in LabEx labs!

0 Comments

no data
Be the first to share your comment!