Syntax knowledge of shell scripts--Numerical calculation

Source: Internet
Author: User

①$[]

  $[$a operator $b]

Example: a=2;b=3;

echo $[$a + $b] # 5

echo $[$a-$b] #-3

echo $[++ $a-$b] #0

c=$[$a + $b] #√c=6

D=$[A+B] # 6

  Note: Except that the self-add-decrement operator is supported; only integer operations can be performed; + + does not error or self-add in front of the operand; $[] outputs the result of the operation

②let

Let A=b+c

Example: a=1;b=2;

Let C=a+b;echo $c # 3

Let C=++a+b;echo $c # 4

C=let a+b #xlet does not output calculation results

Echo ' Let A+b ' #x

  Note: Almost all operators are supported; the variable in the expression does not add $; In general, the expression is not enclosed in double quotes, but if the expression has the Bash keyword, it must be added; only integer operations are allowed; Let does not output the result of the operation, and the assignment needs to be done in the expression; bash built-in command

③[$] (())

Cases:

A=3;

((b=a+2)); Echo $b # 5

Echo ((a+5)) or c= ((a+3)) #-bash:syntax error near unexpected token ' ('

echo $ ((a+5)) or c=$ ((a+3)); Echo $c # 8 or 6

  Note: The usage is exactly the same as let, if the $ symbol is preceded, the result is output, otherwise the result is not output

④bc

Cases:

F= ' echo 3+1|BC '; Echo $f # 4

Touch F;echo 3+4 > F;cat F |BC # 7

  Note: Supports floating-point calculation; supports all operations except bitwise operations; precision setting by scale

⑤expr

Cases:

A=3;

b= ' expr $a + 3 '; Echo $b # 6

  Note: Some operators need to be escaped; the operator and operand are separated by a space; only integer operations are supported

Syntax knowledge of shell scripts--Numerical calculation

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.