shell腳本引用外部變量方法


  • 本地變量只能在當前bash進程中有效,對當前shell之外的其它進程,包括子進程均無效。而啓動腳本實際就是開啓一個子進程執行命令,所以,在腳本里就無法引用父進程上的本地變量。如下,引用外部變量失敗:
[root@centos7 test]#echo $var
yes
[root@centos7 test]#bash test.sh 

[root@centos7 test]#

  • 那如何在腳本中引用外部變量呢,有兩種方法可以實現
  1. 第一種:把變量設置成環境變量
[root@centos7 test]#export var
[root@centos7 test]#bash test.sh 
yes
[root@centos7 test]#

  1. 第二種:用source方式啓動腳本(或者用. /path/name.sh;注意點號和斜槓之間必須有空格,若沒有空格就是直接執行腳本,是不一樣的),這種方式不會開啓子進程,而是把腳本加載到當前進程中執行,所以也就能引用當前進程中的本地變量了。
[root@centos7 test]#newvar="no"
[root@centos7 test]#source test.sh 
no
[root@centos7 test]#. test.sh 
no
[root@centos7 test]#



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章