Multiple ways to perform mathematical operations through the shell _linux shell

Source: Internet
Author: User

In bash, Bash's math is a little awkward, it's hard to adapt and remember, so you have to write a blog post to make it easier to look through. There are four ways to perform mathematical operations:

A, let order

Copy Code code as follows:

#/bin/bash
Num1=13
Num2=14
Let sum= $num 1+ $num 2

Echo $sum

#自增
Let sum++

#自减
Let sum--

#简写形式
Let Sum+=1
Let sum-=2

#顺便吐槽下, let sum= (1+3) * (2+2) Incredibly not, really rotten there!

II, $[] form

Copy Code code as follows:

#!/bin/bash
sum = $[99+88]

#[] also uses variables
num1=11
Num2=22
sum=$[$num 1+ $num 2]

Three, $ (()) way

Copy Code code as follows:

#!/bin/bash
sum=$ ((1+2))

# $ (()) can be used () for priority operation arrangement
Sum=$ (((1+2) *3))
Echo $sum #9

Iv. You can also use the expr command, which requires an operand and an operation symbol to be empty

Copy Code code as follows:

#!/bin/bash
Expr 3 + 4 #7

sum= ' expr ' #33后有空格, "+" after a space, if the writing is sum= ' expr 3+4 ', echo $sum will be 33+44
Echo $sum #77

The above 4 kinds of methods do not support floating-point operations, to carry out floating-point operations, you should use the BC command, syntax format is relatively simple:

Copy Code code as follows:

#!/bin/bash

Sum= ' echo 222.222+333.333 | BC '
Echo $sum

#sum = ' echo 12.228222+ (22222*2) | BC ' incredibly not, decisively despise it.

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.