您的位置:首页 > 运维架构 > Shell

shell变量计算长度及加减运算方法总结

2017-04-30 22:33 585 查看

linux shell 变量定义,以及变量的输出,在shell编写中常常需要计算变量的长度,以及数字变量直接进行加减操作

变量定义

shell变量没有整形,字符串,浮点型等其余编程语言定义的数据类型

[root@mytest ~]# str=string


str是一个变量

变量输出

[root@mytest ~]# echo $str
string
或:
[root@mytest ~]# echo ${str}
string


变量常常需要计算字符的长度:

shell计算长度方式:

${#str}

[root@mytest ~]# echo ${#str}
6


特殊的变量:

当前的shell类型:

[root@mytest ~]# echo $SHELL
/bin/bash
[root@mytest ~]# echo $0
-bash


判断是否是超级用户

[root@mytest ~]# echo $UID
0
例如:
if [ $UID -ne 0 ];then
echo 'not super root'
else
echo 'root user'
fi


shell变量若是数字,常常也需要进行数学运算:

a=1

b=5

1.let直接进行计算

[root@mytest ~]# a=1
[root@mytest ~]# b=5
[root@mytest ~]# let c=a+b
[root@mytest ~]# echo $c
6


自增与自减

[root@mytest ~]# let c++
[root@mytest ~]# echo $c
7
[root@mytest ~]# let c--
[root@mytest ~]# echo $c
6


简写:

[root@mytest ~]# let c+=5
[root@mytest ~]# echo $c
11


2.操作符[]

[root@mytest ~]# d=$[ a+b ]
[root@mytest ~]# echo $d
6


也可以使用$

[root@mytest ~]# echo $[ $d+5 ]
11
[root@mytest ~]# echo $[ $d+$a ]
7


3.符号(())

[root@mytest ~]# echo $((a+19))
20
[root@mytest ~]# echo $((a+b))
6


4.expr 也可以用于基本的算数计算

[root@mytest ~]# echo `expr 2 + 6`
8
[root@mytest ~]# echo $(expr $a + 19)
20


也可以用两个变量

[root@mytest ~]# echo $(expr $a + $b)
6


需要注意,expr需要带上$变量符号,否则有报错,无法得出计算结果

[root@mytest ~]# echo $(expr a + b)
expr: non-integer argument
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息