Shell Script--Numerical calculation

Source: Internet
Author: User

Native bash does not support simple math operations

When you are beginner, you can use $ (()) and expr to implement

Use $ (()) to achieve:

#!/bin/bash# file name: Test.shecho $ ((1+3)) #命令行第2个参数和第3个参数求和 # At this point the + number can be added without spaces echo $ (($1+$2)) echo $ (($ + $)) echo $ (($1-$2)) echo $ (($1*$2)) #此时不用对 * Escape echo $ (($1/$2)) echo $ (($1%$2))

Execute script:

  

Use expr to implement:

#!/bin/bash# file name: test.sh#expr is a command for numeric calculations # at which point the operation symbol must be blank, no space will be output as is, and the expr 1 + 3# command line 2nd and 3rd arguments will not be evaluated sum expr + $2expr $-$ 2EXPR $ * $    #失败expr $ \* $   #因为乘号 * There is a special meaning in the shell, so you want to escape expr $/$    #除法取商expr $    #除法取模

To run the script:

  

Before using expr to understand the function of anti-quotation marks, the function of anti-quotes is to execute the contents of the inverted quotation mark, that is, to execute, which means that the anti-quotation mark is a command, and the anti-quotation marks can not be used alone, to include the anti-quote and its enclosed statement to assign a variable, otherwise an error If you do not want to assign it to a variable, do not use anti-quotation marks to write the contents of the quotation marks directly, because the content is a command.

#!/bin/bash# file name: test.sh# You must add a space on either side of the operation symbol # The result of the command in the anti-quotation mark must be assigned to a variable num= ' expr 1 + 3 ' echo $num # command line 2nd argument and 3rd argument sum num= ' expr $ + $ ' echo $num # multiplication operator still to escape num= ' expr $ \* ' echo $num

To run the script:

  

Shell Script--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.