1. 程式人生 > >小鳥初學Shell程式設計(七)變數引用及作用範圍

小鳥初學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 變數名來清空變數的值