快速入门Shell编程(七)变量引用及作用范围

变量引用

那么定义好变量,如何打印变量的值呢?举例下变量引用的方式。

  • ${变量名}称作为对变量的引用
  • echo ${变量名}查看变量的值
  • ${变量名}在部分情况下可以省略成 $变量名
[root@lincoding ~]# string="hello Shell"
[root@lincoding ~]# echo ${string}
hello Shell
[root@lincoding ~]# echo $string
hello Shell

那么有花括号括起来的变量和没有花括号的区别是什么呢?

[root@lincoding ~]# echo $string9

[root@lincoding ~]# echo ${string}9
hello Shell9

可以发现在引用string变量后加了个9,没有加花括号的引用,会把string9当做一个变量名,有加花括号的引用,则在打印string变量后,尾部多增加一个9


变量的默认作用范围

我们通过定义的变量只会在当前的Shell环境生效,当切换成另外一个Shell的时候,之前定义好的变量是不生效的

我们在Shell脚本里定义了一个变量str

#!/bin/bash

str="my shell"
echo ${str}

执行Shell脚本的时候,会打印在Shell脚本定义的变量的值。当前终端引用了Shell脚本的变量,打印了空值。

[root@lincoding ~]# ./test.sh
my shell
[root@lincoding ~]# echo ${str}

[root@lincoding ~]#

说明变量str作用范围只在Shell脚本里。

如果在终端定义个一变量,Shell脚本里引用该变量会生效吗?

[root@lincoding ~]# mystr="abc"
[root@lincoding ~]# cat test.sh
#!/bin/bash

echo ${mystr}
[root@lincoding ~]# ./test.sh

[root@lincoding ~]# bash test.sh

[root@lincoding ~]# . test.sh
abc
[root@lincoding ~]# source test.sh
abc

上面分别使用了四种执行方式运行脚本,这四种执行方式的影响也在前面章节详细说明过。

方式一和方式二,是会产生子进程来执行脚本,由于当前终端定义的变量作用范围只在当前的终端,所以子进程引用于父进程定义的变量是不生效的。

方式三和方式四,是不会产生子进程,而是直接在当前终端环境执行脚本,所以也在变量的作用范围内,所以引用了变量是生效的。


export导出变量

假设想让父进程定义的变量在子进程或子Shell也同时生效的话,那么需要用export将变量导出,使用的具体方式如下例子:

[root@lincoding ~]# mystr="abc"
[root@lincoding ~]# bash test.sh

[root@lincoding ~]# export mystr
[root@lincoding ~]# bash test.sh
abc
[root@lincoding ~]# ./test.sh
abc

可见在使用export后,终端定义的变量,test.sh脚本里引用了该变量是生效的。也就说子进程可以获取父进程定义的变量的值。

如果用完了该变量,想把变量清空,则可以使用unset

[root@lincoding ~]# unset mystr
[root@lincoding ~]# echo ${mystr}

[root@lincoding ~]#

小结

变量默认的作用范围是Shell的自身,如果想为子Shell或子进程来使用父进程的变量,我们需要用export 变量名关键词进行导出变量,如果不再使用该变量,要及时使用unset 变量名来清空变量的值。

发布了40 篇原创文章 · 获赞 18 · 访问量 3877

猜你喜欢

转载自blog.csdn.net/qq_34827674/article/details/101854913
今日推荐