Shell Mathematical Expression

Source: Internet
Author: User

By default, operations in Shell programs are string operations, and unexpected answers may be obtained when you want to run mathematical operators:

Var = 1
Var = $ var + 1
Echo $ VaR

Output:
1 + 1

From this example, we can see that the shell string connection operation requires spaces. In Shell, let can be used to indicate the following arithmetic expressions:

Var = 1
Let "Var + = 1"
Echo $ VaR

Output:
2

Here, Let can be replaced by (), just as it is used in many cycles:

Var = 1
(VAR ++ ))
Echo $ VaR

Output:
2

There is also a way to write:

Var = 1
Var = $ [$ var + 1]
Echo $ VaR

Output:
2

When using expr, note that the symbol is not a single quotation mark, but the key on the left of "1:

Var = 1
Var = 'expr $ var + 1'
Echo $ VaR

Output:
2

The above methods can only process integer operations. The following method can process floating point numbers:

Var = 1
Var = 'echo "$ Var * 2.0" | BC'
Echo $ VaR

Output:
2.0

The 'symbol above is the same as the one on the left, while BC is a calculator on Linux. It supports all operations except bit operations. Another method that supports floating-point operations is awk:

Var = 1
Var = 'echo "$ var 1" | awk '{printf ("% G", $1 + $2 )}''
Echo $ VaR

Output:
2

The above are some of the methods we have just seen. I will try again later.

--------------

Welcome to shoot bricks.

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.