深浅模式
自定义变量
基本语法
- 定义变量:变量名=变量值,注意,=号前后不能有空格
- 撤销变量:unset 变量名
- 声明静态变量:readonly 变量,注意:不能 unset
变量定义规则
- 变量名称可以由字母、数字和下划线组成,但是不能以数字开头,环境变量名建 议大写
- 等号两侧不能有空格
- 在 bash 中,变量默认类型都是字符串类型,无法直接进行数值运算。
- 变量的值如果有空格,需要使用双引号或单引号括起来
案例实操
(1)定义变量 A
shell
[root@centos7 ~]# A=5
[root@centos7 ~]# echo $A
5(2)给变量 A 重新赋值
shell
[root@centos7 ~]# A=8
[root@centos7 ~]# echo $A
8(3)撤销变量 A
shell
[root@centos7 ~]# unset A
[root@centos7 ~]# echo $A(4)声明静态的变量 B=2,不能 unset
shell
[root@centos7 ~]# readonly B=2
[root@centos7 ~]# echo $B
2
[root@centos7 ~]# B=8
-bash: B: 只读变量(5)在 bash 中,变量默认类型都是字符串类型,无法直接进行数值运算
shell
[root@centos7 ~]# C=1+2
[root@centos7 ~]# echo $C
1+2(6)变量的值如果有空格,需要使用双引号或单引号括起来
shell
[root@centos7 ~]# D=I love shell
bash: love: 未找到命令...
[root@centos7 ~]# D="I love shell"
[root@centos7 ~]# echo $D
I love shell(7)可把变量提升为全局环境变量,可供其他 Shell
shell
export 变量名
[root@centos7 ~]#在 helloworld.sh 文件中增加 echo $B
shell
#!/bin/bash
echo "helloworld"
echo $Bshell
[root@centos7 ~]# ./helloworld.sh
Helloworld发现并没有打印输出变量 B 的值。
shell
[root@centos7 ~]# export B
[root@centos7 ~]# ./helloworld.sh
helloworld
2