(五)shell变量声明和使用

10:Shell 的运算符

(1)数值运算的方法

那如果我需要进行数值运算,可以采用以下三种方法中的任意一种:使用 declare 声明变量类型,既然所有变量的默认类型是字符串型,那么只要我们把变量声明为整数型不就可以运算了吗?使用declare 命令就可以实现声明变量的类型。命令如下:

[root@localhost ~]# declare [+/-][选项]

变量名选项:

-: 给变量设定类型属性

+: 取消变量的类型属性

-a:  将变量声明为数组型

-i:  将变量声明为整数型(integer)

-r:  讲变量声明为只读变量。注意,一旦设置为只读变量,既不能修改变量的值,也不能删除变量,甚至不能通过+r 取消只读属性.

-x:  将变量声明为环境变量

扫描二维码关注公众号,回复: 7458907 查看本文章

-p:  显示指定变量的被声明的类型

 

例子1:声明变量类型进行运算

[root@localhost ~]# aa=11

[root@localhost ~]# bb=22

#给变量 aa 和 bb 赋值

[root@localhost ~]# declare -i cc=$aa+$bb

#声明变量 cc 的类型是整数型,它的值是 aa 和 bb 的和

[root@localhost ~]# echo $cc

33

#这下终于可以相加了

 

例子 2:数组变量类型

注意数组的下标是从 0 开始的,在调用数组值时,需要使用${数组[下标]}的方式来读取。

[root@localhost ~]# name[0]="li "

 [root@localhost ~]# name[1]="ming"

 [root@localhost ~]# name[2]=" ang"

 [root@localhost ~]# echo ${name}

li

#输出数组的内容,如果只写数组名,那么只会输出第一个下标变量

[root@localhost ~]# echo ${name[*]}

li ming ang

 

例子 3: 环境变量

我们其实也可以使用 declare 命令把变量声明为环境变量,和 export 命令的作用是一样的:

[root@localhost ~]# declare -x test=123

#把变量 test 声明为环境变量

 

例子 4:只读属性

注意一旦给变量设定了只读属性,那么这个变量既不能修改变量的值,也不能删除变量,甚至不能使用“+r”选项取消只读属性。命令如下:

[root@localhost ~]# declare -r test

#给 test 赋予只读属性

[root@localhost ~]# test=456

-bash: test: readonly variable

#test 变量的值就不能修改了

[root@localhost ~]# declare +r test

-bash: declare: test: readonly variable

#也不能取消只读属性

[root@localhost ~]# unset test

-bash: unset: test: cannot unset: readonly variable

#也不能删除变量.

 

 

例子 5:查询变量属性和取消变量属性

变量属性的查询使用“-p”选项,变量属性的取消使用“+”选项。命令如下:

[root@localhost ~]# declare -p cc

declare -i cc="33"

#cc 变量是 int 型

[root@localhost ~]# declare -p name

declare -a name='([0]=" li " [1]="li " [2]="ming")'

#name 变量是数组型

[root@localhost ~]# declare -p test

declare -rx test="123"

#test 变量是环境变量和只读变量

[root@localhost ~]# declare +x test

#取消 test 变量的环境变量属性

[root@localhost ~]# declare -p test

declare -r test="123"

#注意,只读变量属性是不能取消的.

 

例子6:shell运算

Shell 进行算运算:

(1)$(( $num1 + $num2 ))

(2)declare –i声明变量是整形

(3)dd=$(expr $aa + $bb)

#dd 的值是 aa 和 bb 的和。注意“+”号左右两侧必须有空格

(4)let ee=$aa+$bb 

(5)gg=$[ .

+$bb ]

 

Shell运算符:

13  -, +  单目负、单目正

12  !, ~  逻辑非、按位取反或补码

11  * , / , %  乘、除、取模

10  +, -  加、减

9  << , >>  按位左移、按位右移

8  < =, > =, < , >  小于或等于、大于或等于、小于、大于

7  == , !=  等于、不等于

/*    &  按位与/

5  ^  按位异或

4  |  按位或

3  &&  逻辑与

2  ||  逻辑或

1    =,+=,-=,*=,/=,%=,&=, ^=, |=, <<=, >>=  赋值、运算且赋

基本上:常用的四则运算,&&,||,

异或运算:二进制运算,& 有0为0 ,| 有1为1

 

变量的测试与内容置换:

测试变量是否有数值:

情况:

(1)变量没有声明,echo输出是空。 set –u echo $name没有会报错,程序的识别需要用到shell自带的测试

(2)变量声明 name=””为空

x=${y-新值}  x=新值  x 为空  x=$y

如果 y没有声明 x=new

如果 y=”” x=空

如果 y=123 x=123

猜你喜欢

转载自www.cnblogs.com/love-life-insist/p/11668769.html