In Previous Years Questions
The expr command is a built-in command in Linux that evaluates arithmetic expressions and string comparisons. It is a simple and versatile tool for performing calculations and comparisons on the command line.
Some of the uses of expr command:
- Basic arithmetic operations: Addition, subtraction, multiplication, division, and modulus.
- Comparisons: Equality, inequality, greater than, less than, greater than or equal to, less than or equal to.
- String operations: Length of a string, extracting a substring, comparing strings.
- Combining expressions: Use parentheses to combine multiple expressions.
Example 1: Adding two numbers:
expr 10 + 5
This command will output the sum of 10 and 5, which is 15.
Example 2: Subtracting two numbers:
expr 20 - 7
This command will output the difference of 20 and 7, which is 13.
Example 3: Multiplying two numbers:
expr 3 * 4
This command will output the product of 3 and 4, which is 12.
Example 4: Dividing two numbers:
expr 12 / 3
This command will output the quotient of 12 and 3, which is 4.
Example 5: Finding the length of a string:
expr length "Hello World"
This command will output the length of the string “Hello World”, which is 11.
Example 6: Extracting a substring:
expr substr "This is a string" 5 4
This command will output the substring starting at the 5th character (index 4) of the string “This is a string”, with a length of 4 characters. The output will be “is a”.
Example 7: Comparing two strings:
expr "apple" == "banana"
This command will compare the strings “apple” and “banana”. Since they are not equal, the output will be 0.
Example 8: Combining expressions:
expr \( 10 + 5\ )\ * 2
This command will first evaluate the expression inside the parentheses (10 + 5), then multiply the result by 2. The output will be 30.