There are four ways to do the Bash Shell's arithmetic operations.

Source: Internet
Author: User
Tags arithmetic

No.1: Using expr
eg. R= ' Expr 4 + 5 '
Echo $r
Note : There should be a space between the operators and operands in the 4 + 5 expression

# finally found the reason, to force Ah.

In addition, for multiplication operator *, use expr needs to be added \ To escape that is r= ' expr 4 \* 5 '
PS: no power-* operation in expr expression

No.2: Use $ (())
eg. r=$ ((4 + 5))
Echo $r
Note: $ (there is no space between, (()) Two pairs of parentheses there is no space between

No.3: Using $[]
eg. R=$[4 + 5]
Echo $r
Note: There are no spaces between $[

No.4: Using Let
eg. Let A=4+5
Echo $a
Note: a=4+5 This expression is the same as a normal arithmetic expression, with no spaces

Examples:
Multiplication:
R= ' Expr 4 \* 5 '
Echo $r
r=$ ((4 * 5))
Echo $r
r=$[4 * 5]
Echo $r
Let R=4*5
Echo $r
4 outputs are: 20

Division:
r= ' Expr 40/5 '
Echo $r
r=$ ((40/5))
Echo $r
r=$[40/5]
Echo $r
Let R=40/5
Echo $r
4 Outputs are: 8

Minus method:
r= ' Expr 40-5 '
Echo $r
r=$ ((40-5))
Echo $r
r=$[40-5]
Echo $r
Let r=40-5
Echo $r
4 outputs are: 35

Take the mold:
r= ' Expr 100% 43 '
Echo $r
r=$ ((100% 43))
Echo $r
r=$[100% 43]
Echo $r
Let r=100%43
Echo $r
4 outputs are: 14

By 冪 (such as 2 of the 3-time Party):
r=$ ((2 * * 3))
Echo $r
r=$[2 * * 3]
Echo $r
Let R=2**3
Echo $r
4 Outputs are: 8
Note: Expr does not multiply 冪

Although the bash shell has several arithmetic operations, not every method can be cross-platform, so that the script can be used across platforms, preferably with ' expr expression ' or $ (()), the Linux design 3rd book recommends using $ (()).

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.