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

  • Post author:
  • Post category:其他


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



版权声明:本文为comprel原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。