Saturday, January 18, 2025
HomeProgrammingWhat is Expr Command in Linux?

What is Expr Command in Linux?

The expr command in Linux is used for evaluating expressions, which can include arithmetic, string operations, and comparisons. It’s a simple utility for performing basic calculations and tests in shell scripts or directly in the terminal.

Here’s a breakdown of some common uses of expr:

1. Arithmetic Operations

  • Addition:
    expr 5 + 3
    

    Output: 8

  • Subtraction:
    expr 5 - 3
    

    Output: 2

  • Multiplication:
    expr 5 \* 3
    

    Output: 15

  • Division:
    expr 10 / 2
    

    Output: 5

  • Modulo (remainder of division):
    expr 10 % 3
    

    Output: 1

Note: You need to escape the * symbol with a backslash (\*) because it is a wildcard character in the shell.

2. String Operations

  • Length of a string:
    expr length "Hello"
    

    Output: 5 (length of the string “Hello”)

  • Substring extraction:
    expr substr "Hello, world!" 1 5
    

    Output: Hello (starts from position 1, length 5)

3. Comparison Operations

  • Equal to:
    expr 5 = 5
    

    Output: 1 (true, because 5 is equal to 5)

  • Not equal to:
    expr 5 != 3
    

    Output: 1 (true, because 5 is not equal to 3)

  • Greater than:
    expr 5 \> 3
    

    Output: 1 (true, because 5 is greater than 3)

  • Less than:
    expr 5 \< 8
    

    Output: 1 (true, because 5 is less than 8)

Note: In comparison operations, escape characters (\>, \<) are required because > and < have special meanings in the shell.

4. Logical Operations

  • Logical AND (&&):
    expr 5 \> 3 : && expr 4 \> 3
    

    This checks if both conditions are true.

  • Logical OR (||): Similar usage as AND but with || in a conditional structure.

5. Using expr with Variables

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

Output: 8 (evaluates the expression using variables)

Important Notes:

  • expr evaluates the expressions in a way similar to the shell’s built-in syntax but is more limited in scope.
  • Each operation in expr generally requires spaces between operands.
  • It is now somewhat outdated and has been largely replaced by more advanced alternatives (e.g., (( )) for arithmetic in Bash, or awk for more complex tasks).

Would you like to see more advanced examples or applications of expr?

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x