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