在shell中,变量大部分情况下不需要声明,可以直接赋值;默认值是字符串类型。变量名必须以字符或下划线_开头,且区分大小写。
1、变量类型:
1.1、自定义变量
1.1.1、定义变量
变量名=变量值
1.1.2、引用变量
$变量名 或
${变量名} 变量名被括号括起来可以避免在一些情况下引起歧义。
1.1.3、查看变量
echo $变量名 ${变量名}
set | grep 变量名
set 显示所有变量,包括自定义变量和环境变量
1.1.4、取消变量
unset 变量名
1.1.5、变量作用范围
当前shell环境
1.1.6、实例
##定义变量
[root@centos6 ~]# a=666
[root@centos6 ~]#
[root@centos6 ~]# echo $a
666
[root@centos6 ~]# echo ${a}
666
[root@centos6 ~]#
##引起歧义,导致变量a没有被显示
[root@centos6 ~]# echo $ab
##加{}避免歧义,变量显示正常
[root@centos6 ~]# echo ${a}b
666b
[root@centos6 ~]#
[root@centos6 ~]# set|grep ^a=
a=666
[root@centos6 ~]# vi test.sh
[root@centos6 ~]# cat test.sh
#!/bin/bash
echo $a
##执行shell脚本,在子shell执行,变量值没有显示
[root@centos6 ~]# ./test.sh
[root@centos6 ~]#
##在当前shell执行脚本,显示变量值
[root@centos6 ~]# . ./test.sh
666
[root@centos6 ~]#
##取消变量
[root@centos6 ~]# unset a
[root@centos6 ~]#
[root@centos6 ~]# echo $a
1.2、环境变量
1.2.1、定义变量
export 变量名=变量值
export 自定义变量名
1.2.2、引用变量
$变量名 或
${变量名} 变量名被括号括起来可以避免在一些情况下引起歧义。
1.2.3、查看变量
echo $变量名 ${变量名}
set | grep 变量名
env |grep 变量名
env 显示所有环境变量
1.2.4、取消变量
unset 变量名
1.2.5、变量作用范围
当前shell和子shell环境
1.2.6、实例
[root@centos6 ~]# a=666
[root@centos6 ~]#
##定义环境变量
[root@centos6 ~]# export a
[root@centos6 ~]# export bb="test env"
[root@centos6 ~]#
##查看环境变量
[root@centos6 ~]# echo $a $bb
666 test env
[root@centos6 ~]#
[root@centos6 ~]# vi test.sh
[root@centos6 ~]# cat test.sh
#!/bin/bash
echo $a
echo $bb
[root@centos6 ~]#
## 在子shell中查看变量
[root@centos6 ~]# ./test.sh
666
test env
[root@centos6 ~]#
##在当前shell中查看变量
[root@centos6 ~]# . ./test.sh
666
test env
[root@centos6 ~]#
##取消变量
[root@centos6 ~