数值类型

数值类型

我们可以使用如下方式创建数值类型变量:

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"

数学计算

您可以对 Bash Shell 变量执行数学运算。bash shell 具有内置的算术选项。您还可以使用外部命令,例如 expr 和 bc 计算器。通过使用以下格式放置整数表达式来完成算术扩展和求值:

$((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.

使用 x 和 y 变量加两个数字。使用文本编辑器创建一个名为 add.sh 的 Shell 程序:

#!/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

运算符按优先级顺序进行评估。这些级别按优先级从高到低的顺序列出(引用 bash 手册页中的内容):

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
上一页
下一页