当前位置:网站首页>Shell basic operator -- arithmetic operator

Shell basic operator -- arithmetic operator

2022-06-24 08:37:00 Chen Bucheng I

Shell Like any programming language , Support for multiple operators , Include :

  • Arithmetic operator
  • Relational operator
  • Boolean operator
  • String operators
  • File test operators

Native bash Simple mathematical operations are not supported , But you can do it with other commands , for example awk and expr,expr The most commonly used .expr Is an expression calculation tool , It can be used to evaluate expressions . Add two numbers ( Note the use of back quotes ` Not single quotes ') example

  1. #!/bin/bash
  2. val=`expr 2 + 2`
  3. echo " The sum of the two is : $val"

Execute the script , The output is as follows :

  1. The sum of the two is :4

Two points attention : Space between expression and operator , for example 2+2 It is not right , Must be written as 2 + 2, This is different from most programming languages we are familiar with . The complete expression is to be ` ` contain , Note that this character is not a common single quotation mark , stay Esc Key bottom .

Arithmetic operator

The following table lists the common arithmetic operators , Assumed variable a by 10, Variable b by 20:

Operator

explain

give an example

+

Add

`expr $a + $b` The result is 30.

-

Subtraction

`expr $a - $b` The result is -10.

*

Multiplication

`expr $a * $b` The result is 200.

/

division

`expr $b / $a` The result is 2.

%

Remainder

`expr $b % $a` The result is 0.

=

assignment

a=$b Will put the variable b The value is assigned to a.

==

equal . Used to compare two numbers , Same returns true.

[ $a == $b ] return false.

!=

It's not equal . Used to compare two numbers , If not, return to true.

[ $a != $b ] return true.

Be careful : Conditional expressions should be placed between square brackets , And there should be spaces , for example : [$a$b] It's wrong. , Must be written as [ $a$b ]. Examples of arithmetic operators are as follows :

  1. #!/bin/bash
  2. a=10
  3. b=20
  4. val=`expr $a + $b`
  5. echo "a + b : $val"
  6. val=`expr $a - $b`
  7. echo "a - b : $val"
  8. val=`expr $a \* $b`
  9. echo "a * b : $val"
  10. val=`expr $b / $a`
  11. echo "b / a : $val"
  12. val=`expr $b % $a`
  13. echo "b % a : $val"
  14. if[ $a == $b ]
  15. then
  16. echo "a be equal to b"
  17. fi
  18. if[ $a != $b ]
  19. then
  20. echo "a It's not equal to b"
  21. fi

Execute the script , The output is as follows :

  1. a + b :30
  2. a - b :-10
  3. a * b :200
  4. b / a :2
  5. b % a :0
  6. a It's not equal to b

Be careful :

Multiplication sign (*) There must be a backslash in the front (\) To achieve multiplication ;

原网站

版权声明
本文为[Chen Bucheng I]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/06/20210622172020539h.html