Use of expr in the shell

Source: Internet
Author: User
Tags arithmetic arithmetic operators

The expr command takes an arithmetic expression as a parameter, usually in the following form:

expr [number] [operator] [number]


Because the shell stores variables as characters, the user must ensure that the operand that participates in the arithmetic operation must be numeric. The following are valid arithmetic operators:


+ two integers added

-first number minus second number

* Multiply two integers

/First integer divided by second integer

% two integers divide, take remainder

For example:

[Root@mail root]# expr 2 + 1

Results showed: 3

[Root@mail root]# expr 5-3

Results showed: 2


If one of the arguments to expr is a variable, replace the variable name with the variable value before the expression evaluates.

[Root@mail root]# int=3

[Root@mail root]# expr $int + 4

Results showed: 7

Users can not simply use "*" to do multiplication, if input:

[Root@mail root]# expr 4*5

The system will get an error, because the shell will see "*" to replace the file name first. The correct form is:

[[email protected] root]# Expr 4 \* 5

Results showed: 20

Multiple arithmetic expressions can be grouped together, for example:

[[email protected] root]# Expr 5 + 7/3

Results showed: 7

The order of operations is preceded by multiplication, and to change the order of operations, the "'" number must be used, such as:

[[email protected] root]# int= ' expr 5 + 7 '

[[email protected] root]# expr $int/3

Results showed: 4

Or:

[[email protected] root]# expr ' expr 5+7 '/3

Results showed: 4

Use of expr in the shell

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.