加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

小鸟初学Shell编程(七)变量引用及作用范围

发布时间:2020-12-16 01:39:52 所属栏目:安全 来源:网络整理
导读:变量引用 那么定义好变量,如何打印变量的值呢?举例下变量引用的方式。 ${变量名} 称作为对变量的引用 echo ${变量名} 查看变量的值 ${变量名} 在部分情况下可以省略成 $变量名 [[email?protected] ~]# string="hello Shell"[[email?protected] ~]# echo ${

变量引用

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

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

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

[[email?protected] ~]# echo $string9

[[email?protected] ~]# echo ${string}9
hello Shell9

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


变量的默认作用范围

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

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

#!/bin/bash

str="my shell"
echo ${str}

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

[[email?protected] ~]# ./test.sh
my shell
[[email?protected] ~]# echo ${str}

[[email?protected] ~]#

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

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

[[email?protected] ~]# mystr="abc"
[[email?protected] ~]# cat test.sh
#!/bin/bash

echo ${mystr}
[[email?protected] ~]# ./test.sh

[[email?protected] ~]# bash test.sh

[[email?protected] ~]# . test.sh
abc
[[email?protected] ~]# source test.sh
abc

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

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

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


export导出变量

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

[[email?protected] ~]# mystr="abc"
[[email?protected] ~]# bash test.sh

[[email?protected] ~]# export mystr
[[email?protected] ~]# bash test.sh
abc
[[email?protected] ~]# ./test.sh
abc

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

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

[[email?protected] ~]# unset mystr
[[email?protected] ~]# echo ${mystr}

[[email?protected] ~]#

小结

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读