数值类型
数值类型
我们可以使用如下方式创建数值类型变量:
declare -i y=10
echo $y
#!/bin/bash
# set x,y and z to an integer data type
declare -i x=10
declare -i y=10
declare -i z=0
z=$(( x + y ))
echo "$x + $y = $z"
# try setting to character 'a'
x=a
z=$(( x + y ))
echo "$x + $y = $z"
数学计算
您可以对
$((expression))
$(( n1+n2 ))
$(( n1/n2 ))
$(( n1-n2 ))
((count++)) # increment value of variable 'count' by one.
((total+=current)) # set total = total+current.
((current>max?max=current:max=max)) # ternary expression.
使用
#!/bin/bash
x=5
y=10
ans=$(( x + y ))
echo "$x + $y = $ans"
带整数的数学运算符如下表所示:
Operator | Description | Example | Evaluates To |
---|---|---|---|
+ | Addition | echo $(( 20 + 5 )) | 25 |
- | Subtraction | echo $(( 20 - 5 )) | 15 |
/ | Division | echo $(( 20 / 5 )) | 4 |
* |
Multiplication | echo $(( 20 * 5 )) |
100 |
% | Modulus | echo $(( 20 % 3 )) | 2 |
++ | post-increment (add variable value by 1) | x=5 echo $(( x++ )) echo $(( x++ )) | 5 6 |
– | post-decrement (subtract variable value by 1) | x=5 echo $(( x– )) | 4 |
** |
Exponentiation | x=2 y=3 echo $(( x ** y )) |
8 |
运算符按优先级顺序进行评估。这些级别按优先级从高到低的顺序列出(引用
id++ id--
variable post-increment and post-decrement
++id --id
variable pre-increment and pre-decrement
- + unary minus and plus
! ~ logical and bitwise negation
** exponentiation
* / % multiplication, division, remainder
+ - addition, subtraction
<< >> left and right bitwise shifts
<= >= < >
comparison
== != equality and inequality
& bitwise AND
^ bitwise exclusive OR
| bitwise OR
&& logical AND
|| logical OR
expr?expr:expr
conditional operator
= *= /= %= += -= <<= >>= &= ^= |=
assignment
expr1, expr2
comma