In addition to the basic arithmetic operators, the expr command in Linux supports several other operators for string and logical operations. Here’s a concise overview of the operators you can use with expr:
Arithmetic Operators
-
Addition:
+expr 5 + 3 # Outputs: 8 -
Subtraction:
-expr 5 - 3 # Outputs: 2 -
Multiplication:
*(must be escaped or quoted)expr 5 \* 3 # Outputs: 15 -
Division:
/expr 6 / 3 # Outputs: 2 -
Modulus:
%(remainder of division)expr 5 % 3 # Outputs: 2
String Operators
-
String Length: To find the length of a string, use the
lengthfunction:expr length "Hello" # Outputs: 5 -
String Comparison: You can compare strings using
=or!=:expr "Hello" = "Hello" # Outputs: 1 (true) expr "Hello" != "World" # Outputs: 1 (true)
Logical Operators
-
Logical AND:
&expr 1 \& 1 # Outputs: 1 (true) -
Logical OR:
|expr 0 \| 1 # Outputs: 1 (true)
Comparison Operators
-
Greater Than:
>expr 5 \> 3 # Outputs: 1 (true) -
Less Than:
<expr 5 \< 3 # Outputs: 0 (false) -
Greater Than or Equal To:
>=expr 5 \>= 5 # Outputs: 1 (true) -
Less Than or Equal To:
<=expr 5 \<= 5 # Outputs: 1 (true)
Summary
The expr command is versatile, allowing for various arithmetic, string, and logical operations. Remember to use spaces around operators and escape special characters like *, &, and | to avoid syntax errors.
If you're interested in practicing these operators, consider trying them out in your terminal or exploring related LabEx labs on shell scripting and command-line utilities. Let me know if you have any more questions!
