shell腳本--文件包含


  首先介紹一下shell中包含文件的方法,在C,C++,PHP中都是用include來包含文件,Go和Java使用import來包含(導入)包,而在shell中,很簡單,只需要一個點“.”,然后跟着文件路徑及文件名,或者使用source關鍵字也可以,注意文件路徑可以使用絕對路徑和相對路徑。

  下面是一個文件包含的例子:three.sh包含one.sh和two.sh

#!/bin/bash
#one.sh

one="the is one in file one.sh"

  

#!/bin/bash
#two.sh

two="this is two in file two.sh"

  

#!/bin/bash
#three.sh

#以下包含文件的兩種方法等效,推薦使用source關鍵字
. one.sh 
source two.sh

echo $one
echo $two

  運行結果:

[root@localhost ~]# ./three.sh
the is one in file one.sh
this is two in file two.sh
[root@localhost ~]# 

  

  需要注意的是,一次只能包含一個文件,不要包含多個文件,比如下例中,嘗試使用source一次性包含兩個文件,最終,包含進來的只有第一個文件,后面的文件沒有成功包含

#!/bin/bash
#three.sh

source one.sh two.sh

echo $one
echo $two

  運行結果:

[root@localhost ~]# ./three.sh
the is one in file one.sh

[root@localhost ~]# 

  

  還要注意的是,在其他語言中,重復包含同一個文件(B包含了A,C包含了A和B,造成C包含了A兩次)會報錯,而在shell中是不會報錯的,仍舊會正常運行!!!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM