expr Command in Linux with Examples

This tutorial explains Linux “expr” command, options and its usage with examples.

expr – Evaluates arguments as expressions.

DESCRIPTION

The expr command reads the Expression parameter, evaluates it, and writes the result to standard output.

You must apply the following rules to the Expression parameter:

Separate each term with blanks.
Precede characters special to the shell with a \ (backslash).
Quote strings containing blanks or other special characters.
Integers may be preceded by a unary hyphen. Internally, integers are treated as 32-bit, twos complement numbers.

Note: The expr command returns 0 to indicate a zero value, rather than the null string.

advertisement
advertisement

SYNOPSIS

expr Expression

Expression

expr1 | expr2 results in the value expr1 if expr1 is true; otherwise it results in the value of expr2.
expr1 & results in the value of expr1 if both expressions are true; otherwise it results in 0
expr1 <=
expr1 <
expr1 =
expr1 !=
expr1 >=
expr1 >
If both expr1 and expr2 are numeric, expr compares them as numbers; otherwise it compares them as strings. If the comparison is true, the expression results in 1; otherwise it results in 0.
expr1 +
expr1 –
performs addition or subtraction on the two expressions. If either expression is not a number, expr exits with an error.
expr1 *
expr1 /
expr1 %
performs multiplication, division, or modulus on the two expressions. If either expression is not a number, expr exits with an error. Note that the multiplication symbol (*) is expanded under the KornShell unless you specify it with a leading backslash (\\*), or enclosed in single quotes ('*') or double quotes ("*"). Under command.com you cannot use the backslash to prevent expansion
expr1 : re
match expr1 re
matches the regular expression re against expr1 treated as a string. The regular expression is the same as that accepted by ed, except that the match is always anchored, that is, there is an implied leading ^; therefore expr does not consider ^ to be a metacharacter. If the regular expression contains \(…\) and it matches at least part of expr1, then expr results in only that part; if there is no match, expr results in 0. If the regular expression doesn't contain this construct, then the result is the number of characters matched. The function match performs the same operation as the colon operator.
substr expr1 expr2 expr3 results in the substring of expr1 starting at character position expr2 (origin 1) for the length of expr3 characters.
index expr1 expr2 searches for any of the characters in expr2 in expr1 and returns the first character position (origin 1) at which it finds such a character, or 0 if no such characters are found.
length expr1 returns the length of expr1 in characters.
(expr) groups expressions.

OPERATORS

The valid operators are listed below, grouped in decreasing order of precedence:

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

– + ~ !
Unary minus, unary plus, bit-wise NOT, logical NOT. None of these operands may be applied to string operands, and bit-wise NOT may be applied only to integers.
* / %
Multiply, divide, remainder. None of these operands may be applied to string operands, and remainder may be applied only to integers. The remainder will always have the same sign as the divisor and an absolute value smaller than the divisor.
+ –
Add and subtract. Valid for any numeric operands.
<< >>
Left and right shift. Valid for integer operands only. A right shift always propagates the sign bit.
< > <= >=
Boolean less, greater, less than or equal, and greater than or equal. Each operator produces 1 if the condition is true, 0 otherwise. These operators may be applied to strings as well as numeric operands, in which case string comparison is used.
== !=
Boolean equal and not equal. Each operator produces a zero/one result. Valid for all operand types.
&
Bit-wise AND. Valid for integer operands only.
^
Bit-wise exclusive OR. Valid for integer operands only.
|
Bit-wise OR. Valid for integer operands only.
&&
Logical AND. Produces a 1 result if both operands are non-zero, 0 otherwise. Valid for boolean and numeric (integers or floating-point) operands only.
||
Logical OR. Produces a 0 result if both operands are zero, 1 otherwise. Valid for boolean and numeric (integers or floating-point) operands only.
x?y:z
If-then-else, as in C. If x evaluates to non-zero, then the result is the value of y. Otherwise the result is the value of z. The x operand must have a numeric value.
See the C manual for more details on the results produced by each operator. All of the binary operators group left-to-right within the same precedence level. For example, the command

expr 4*2 < 7 returns 0. The &&, ||, and ?: operators have ``lazy evaluation'', just as in C, which means that operands are not evaluated if they are not needed to determine the outcome. For example, in the command expr {$v ? [a] : [b]} only one of [a] or [b] will actually be evaluated, depending on the value of $v. Note, however, that this is only true if the entire expression is enclosed in braces; otherwise the Tcl parser will evaluate both [a] and [b] before invoking the expr command. MATH FUNCTIONS

It supports the following mathematical functions in expressions:

abs(arg)
Returns the absolute value of arg. Arg may be either integer or floating-point, and the result is returned in the same form.
acos(arg)
Returns the arc cosine of arg, in the range [0,pi] radians. Arg should be in the range [-1,1].
asin(arg)
Returns the arc sine of arg, in the range [-pi/2,pi/2] radians. Arg should be in the range [-1,1].
atan(arg)
Returns the arc tangent of arg, in the range [-pi/2,pi/2] radians.
atan2(x, y)
Returns the arc tangent of y/x, in the range [-pi,pi] radians. x and y cannot both be 0.
ceil(arg)
Returns the smallest integer value not less than arg.
cos(arg)
Returns the cosine of arg, measured in radians.
cosh(arg)
Returns the hyperbolic cosine of arg. If the result would cause an overflow, an error is returned.
double(arg)
If arg is a floating value, returns arg, otherwise converts arg to floating and returns the converted value.
exp(arg)
Returns the exponential of arg, defined as e**arg. If the result would cause an overflow, an error is returned.
floor(arg)
Returns the largest integral value not greater than arg.
fmod(x, y)
Returns the floating-point remainder of the division of x by y. If y is 0, an error is returned.
hypot(x, y)
Computes the length of the hypotenuse of a right-angled triangle (x*x+y*y).
int(arg)
If arg is an integer value, returns arg, otherwise converts arg to integer by truncation and returns the converted value.
log(arg)
Returns the natural logarithm of arg. Arg must be a positive value.
log10(arg)
Returns the base 10 logarithm of arg. Arg must be a positive value.
pow(x, y)
Computes the value of x raised to the power y. If x is negative, y must be an integer value.
rand()
Returns a floating point number from zero to just less than one or, in mathematical terms, the range [0,1). The seed comes from the internal clock of the machine or may be set manual with the srand function.
round(arg)
If arg is an integer value, returns arg, otherwise converts arg to integer by rounding and returns the converted value.
sin(arg)
Returns the sine of arg, measured in radians.
sinh(arg)
Returns the hyperbolic sine of arg. If the result would cause an overflow, an error is returned.
sqrt(arg)
Returns the square root of arg. Arg must be non-negative.
srand(arg)
The arg, which must be an integer, is used to reset the seed for the random number generator. Returns the first random number from that seed. Each interpreter has it’s own seed.
tan(arg)
Returns the tangent of arg, measured in radians.
tanh(arg)
Returns the hyperbolic tangent of arg.

Exit Status

advertisement

This command returns the following exit values:

0
The Expression parameter evaluates to neither null nor 0.
1
The Expression parameter evaluates to null or 0.
2
The Expression parameter is not valid.
>2
An error occurred.

EXAMPLES

1. To modify a shell variable, enter:

 COUNT=`expr $COUNT + 1`

This adds 1 to the shell variable $COUNT. The expr command is enclosed in grave accents, which causes the shell to substitute the standard output from the expr command into the COUNT= command. The $COUNT variable must be initialized before using.

advertisement

2. To find the length of a shell variable

$ echo `expr $VAR : ".*"`

Note : If the $VAR variable is set to the null string or contains any white space (blanks or tabs), then the command displays the error message expr: syntax error.

3. Perform string matching operations

expr command helps us to perform different levels of string matching operations with the operator ‘:’ as shown below,

 
$ expr linux : lin
3
 
 
$ expr linux : linx
0
 
 
$ expr linux : '.*'
5

4. Compare the two expressions

$ var1='10'
$ var2='20'
 
$ expr $var1 = $var2
0
 
$ expr $var1 \< $var2
1
 
$ expr $var1 \!= $var2
1

5. Perform the integer arithmetic operations

$ expr 5 \* 2
10

Sanfoundry Global Education & Learning Series – 1000 Linux Tutorials.

If you wish to look at all Linux commands and their usage examples, go to Linux Commands Tutorial.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.