Shell arithmetic calculation $ (())

Source: Internet
Author: User

From shell 13

 

Well, let's introduce the purpose of $ (): it is used for integer calculation.
In bash, the integer operators of $ () generally include the following:
+-*/: Add, subtract, multiply, and divide respectively ".
%: Remainder operation
& | ^! : "And, Or, XOR, not" operations.

 

~ # A = 1
~ # B = 2
~ # Echo $ (a + B ))
3
~ # Echo $ ($ A + $ B ))
3

 

 

~ # Echo $ (a-B ))
-1
~ # Echo $ (A/B ))
0
~ # Echo $ (A * B ))
2

~ # Echo $ (a % B ))
1

 

 

~ # A = 1
~ # B = 3
~ # Echo $ (A & B ))
1
~ # Echo $ (A | B ))
3
~ # Echo $ (a ^ B ))
2
~ # Echo $ ((! B ))
0
~ # Echo $ ((! A ))
0

 

Example:
[Code] $ A = 5; B = 7; C = 2
$ Echo $ (a + B * C ))
19
$ Echo $ (A + B)/C ))
6
$ Echo $ (A * B) % C ))
1 [/Code]
The variable name in $ () can be replaced by the $ symbol before it or not (which can be supported in busybox)Such:
$ ($ A + $ B * $ C) returns 19 results.

 

In addition, $ () can also be used for different carry (such as binary, octal, and hexadecimal) operations, but the output results are all in decimal format (busybox is not supported ):
Echo $(16 # 2a) returns 42 (hexadecimal to decimal)

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.