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

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
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值