Shell变量之运算符

2017-03-11  本文已影响0人  lupinwu

概述

Shell变量之运算符

1. 课程概述及declare命令

declare命令

[shiyanlou:sh$]aa=11
[shiyanlou:sh$]bb=22
[shiyanlou:sh$]cc=$aa+$bb
[shiyanlou:sh$]declare -i cc=$aa+$bb
[shiyanlou:sh$]echo $cc
33
[shiyanlou:sh$]declare -p cc
declare -i cc="33"
[shiyanlou:sh$]declare -p      *显示所有变量的属性

数组

shiyanlou@localhost:~/sh$ movie[0]=cl
shiyanlou@localhost:~/sh$ movie[1]=tpc
shiyanlou@localhost:~/sh$ declare -a movie[2]=tpb
shiyanlou@localhost:~/sh$ echo ${movie[*]}
cl tpc tpb
shiyanlou@localhost:~/sh$ echo ${movie}
cl
shiyanlou@localhost:~/sh$ echo ${movie[2]}
tpb
shiyanlou@localhost:~/sh$ echo ${movie[*]}
cl tpc tpb

2. 数值运算方法

Linux所有运算符

运算符

expr实现数值运算

shiyanlou@localhost:~/sh$ aa=11
shiyanlou@localhost:~/sh$ bb=22
shiyanlou@localhost:~/sh$ dd=$(expr $aa + $bb)
shiyanlou@localhost:~/sh$ echo $dd
33

$((运算式)) 或 $[运算式]

shiyanlou@localhost:~/sh$ ff=$(( aa+bb ))
shiyanlou@localhost:~/sh$ echo $ff
33
shiyanlou@localhost:~/sh$ gg=$[ $aa+$bb ]
shiyanlou@localhost:~/sh$ echo $gg
33

* 注意与$()区别
shiyanlou@localhost:~/sh$ gg=$(date)
shiyanlou@localhost:~/sh$ echo $gg
Tue Mar 7 13:41:05 CST 2017
shiyanlou@localhost:~/sh$ echo $(( 4+9*3/5 ))
9
shiyanlou@localhost:~/sh$ echo $(( (4+9)*3%5 ))
4
shiyanlou@localhost:~/sh$ echo $(( 16%5 ))
1
shiyanlou@localhost:~/sh$ echo $(( 1&&0 ))
0
shiyanlou@localhost:~/sh$ echo $(( 1&&1 ))
1
shiyanlou@localhost:~/sh$ echo $(( 1||1 ))
1
shiyanlou@localhost:~/sh$ echo $(( 1||0 ))
1
shiyanlou@localhost:~/sh$ echo $(( 0||0 ))
0

3. 变量测试

变量测试公式

变量测试

示例

示例
$ unset y
$ x=${y-2}
$ echo $x
2
$ y=""
$ x=${y-2}
$ echo $x

$ y=1
$ x=${y-2}
$ echo $x
1
上一篇下一篇

猜你喜欢

热点阅读