基本语法
(1)定义变量:变量名=变量值,注意,=号前后不能有空格
(2)撤销变量:unset 变量名
(3)声明静态变量:readonly 变量,注意:不能 unset
定义变量
[root@pwd ~]# a=test
[root@pwd ~]# echo $a
test
[root@pwd ~]# a=test01
[root@pwd ~]# echo $a
test01
[root@pwd ~]# a=test02
[root@pwd ~]# echo $a
test02
[root@pwd ~]#
检查变量的作用范围
开启子shell
[root@pwd ~]# bash
[root@pwd ~]# ps -f
UID PID PPID C STIME TTY TIME CMD
root 11760 11756 0 15:50 pts/1 00:00:00 -bash
root 31308 11760 0 18:27 pts/1 00:00:00 bash
root 31327 31308 0 18:27 pts/1 00:00:00 ps -f
[root@pwd ~]#
再次查看变量
[root@pwd ~]# echo $a
[root@pwd ~]#
退出子Shell
[root@pwd ~]# exit
[root@pwd ~]#
查看变量
[root@pwd ~]# echo $a
test02
上面的案例当中看出,变量范围是局部变量,只能再当前shell进种使用(变量在那个shell中声明就只能在那个shell中使用)
声明全局变量
export 变量名
修改为全局变量
[root@pwd ~]# echo $a
test02
[root@pwd ~]# bash
[root@pwd ~]# echo $a
[root@pwd ~]# exit
[root@pwd ~]# export a
[root@pwd ~]# bash
[root@pwd ~]# echo $a
test02
[root@pwd ~]#
注意:在我们回去变量的值的时候可以使用$变量名称,当我们对变量进行操作的时候直接可以使用变量名称
那么我们如果在子shell中修改变量的值会出现什么情况?
[root@pwd ~]# bash
[root@pwd ~]# echo $a
test02
[root@pwd ~]# a=test03
[root@pwd ~]# echo $a
test03
[root@pwd ~]# exit
[root@pwd ~]# echo $a
test02
[root@pwd ~]#
如果我们在子Shell中定义变量,并设为全局变量,那么能在主shell中访问到吗?
[root@pwd ~]# bash
[root@pwd ~]# echo $a
test02
[root@pwd ~]# a=test03
[root@pwd ~]# echo $a
test03
[root@pwd ~]# exit
[root@pwd ~]# echo $a
test02
[root@pwd ~]#
很显然不能访问,Shell变量的范围是向下的,子Shell只能访问它下面的子Shell,并不能访问它上面的
变量定义规则
(1)变量名称可以由字母、数字和下划线组成,但是不能以数字开头,环境变量名建 议大写。
(2)等号两侧不能有空格
(3)在 bash 中,变量默认类型都是字符串类型,无法直接进行数值运算。
(4)变量的值如果有空格,需要使用双引号或单引号括起来
(5)无法撤销只读变量 unset 变量名称删除普通变量。
[root@pwd ~]# a=123
[root@pwd ~]# echo $a
123
[root@pwd ~]# readonly a
[root@pwd ~]# unset a
-bash: unset: a: cannot unset: readonly variable
[root@pwd ~]#
注意:关闭当前的shell窗口,所有的变量包括全局的、只读的、局部的都会清空。因为这些变量实际上是存储在内存当中的。