shell腳本引用外部變量的兩種方法
本地變量只能在當前bash進程中有效,對當前shell之外的其它進程,包括子進程均無效。而啟動腳本實際就是開啟一個子進程執(zhí)行命令,所以,在腳本里就無法引用父進程上的本地變量。如下,
引用外部變量失?。?/p>
[root@centos7 test]#echo $var yes [root@centos7 test]#bash test.sh? [root@centos7 test]#
那如何在腳本中引用外部變量呢,有兩種方法可以實現(xiàn)
第一種:把變量設置成環(huán)境變量
[root@centos7 test]#export var [root@centos7 test]#bash test.sh yes [root@centos7 test]#
第二種:用source方式啟動腳本(或者用. /path/name.sh;注意點號和斜杠之間必須有空格,若沒有空格就是直接執(zhí)行腳本,是不一樣的),這種方式不會開啟子進程,而是把腳本加載到當前進程中執(zhí)行,所以也就能引用當前進程中的本地變量了。
[root@centos7 test]#newvar="no" [root@centos7 test]#source test.sh no [root@centos7 test]#. test.sh no [root@centos7 test]#
舉例
假設有如下兩個腳本:
main.sh #主腳本 subscripts.sh #子腳本,或者說被調(diào)腳本
subscripts.sh 腳本內(nèi)容如下:
#! /bin/bash ? string="Hello,World! \n"
main.sh 腳本(引用 subscripts.sh 腳本的變量)內(nèi)容如下:
#! /bin/bash ? . ./subscripts.sh ? echo -e ${string} ? exit 0 ?
運行 mian.sh 腳本輸出結果:
# chmod +x main.sh
# ./main.sh
Hello,World!
注意:
- 被調(diào)腳本可以沒有執(zhí)行權限,調(diào)用腳本必須有可執(zhí)行權限。
- 上述例子中是變量的引用,函數(shù)的引用也是一樣的流程。
到此這篇關于shell腳本引用外部變量的兩種方法的文章就介紹到這了,更多相關shell 引用外部變量內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
shell腳本結合iptables防端口掃描的實現(xiàn)
這篇文章主要介紹了shell腳本結合iptables防端口掃描的實現(xiàn),中間使用了inotify-tools工具,需要的朋友可以參考下2014-05-05Linux下/var/run/目錄下的pid文件詳解及pid文件作用
linux系統(tǒng)中/var/run/目錄下的*.pid文件是一個文本文件,其內(nèi)容只有一行,即某個進程的PID。這篇文章主要介紹了Linux下/var/run/目錄下的pid文件詳解及pid文件作用,需要的朋友可以參考下2018-04-04