和其他語言一樣,Shell 也可以包含外部腳本。這樣可以很友善的封裝一些公用的代碼作為一個獨立的檔案。
Shell 檔案包含的文法格式如下:
建立兩個 shell 腳本檔案。
test1.sh 代碼如下:
1
2
<code>#!/bin/bash</code>
<code>url=</code><code>"http://www.baidu.com"</code>
test2.sh 代碼如下:
3
4
5
6
<code>#使用 . 号來引用test1.sh 檔案</code>
<code>. .</code><code>/test1</code><code>.sh</code>
<code># 或者使用以下包含檔案代碼</code>
<code># source ./test1.sh</code>
<code>echo</code> <code>"網址:$url"</code>
接下來,我們為 test2.sh 添加可執行權限并執行:
注:被包含的檔案 test1.sh 不需要可執行權限。
本文轉自 獨孤環宇 51CTO部落格,原文連結:http://blog.51cto.com/snowtiger/1942042