Last Updated : 30 Aug, 2024
The expr command in Unix is a versatile tool used for evaluating expressions in the shell environment. It performs a wide range of functions, including arithmetic calculations, string operations, and comparisons based on regular expressions.
What is the 'expr' Command?expr stands for "expression" and allows for the evaluation of values and returns the result to standard output. It is particularly useful in scripts for handling both numerical and string data efficiently. In short, it helps in:
$expr expression
Key Options:
'expr' Command ExamplesBelow are some examples to demonstrate the use of "expr" command:
1. Using expr for basic arithmetic operations :Example 1: Addition
$expr 12 + 8
Example 2: Multiplication
$expr 12 \* 2
Output
2. Performing operations on variables inside a shell scriptNote: The multiplication operator * must be escaped when used in an arithmetic expression with 'expr'.
Example: Adding two numbers in a script
echo "Enter two numbers" read x read y sum=`expr $x + $y` echo "Sum = $sum"
Output:
3. Comparing two expressionsNote: 'expr' is an external program used by Bourne shell. It uses 'expr' external program with the help of backtick. The backtick(`) is actually called command substitution.
Example 1: Equality Check
x=10 y=20 # matching numbers with '=' res=`expr $x = $y` echo $res # displays 1 when arg1 is less than arg2 res=`expr $x \< $y` echo $res # display 1 when arg1 is not equal to arg2 res=`expr $x \!= $y` echo $res
Output:
Example 2: Evaluating boolean expressions
# OR operation $expr length "geekss" "<" 5 "|" 19 - 6 ">" 10
Output:
# AND operation $expr length "geekss" "<" 5 "&" 19 - 6 ">" 10
Output:
4. For String operationsExample 1: Finding length of a string
x=geeks len=`expr length $x` echo $len
Output:
Example 2: Finding substring of a string
x=geeks sub=`expr substr $x 2 3` #extract 3 characters starting from index 2 echo $sub
Output:
Example 3: Matching number of characters in two strings
$ expr geeks : geek
Output:
ConclusionThe 'expr' command is an indispensable tool for scripting in Unix-like systems, offering a broad array of functionalities from mathematical calculations to complex string manipulations. By mastering 'expr', users can enhance their scripts’ capabilities and perform sophisticated data processing tasks efficiently.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4