和其他語言一樣,Shell 也可以包含外部腳本。這樣可以很方便的封裝一些公用的代碼作為一個獨立的文件。
Shell 文件包含的語法格式如下:
. filename # 注意點號(.)和文件名中間有一空格 或 source filename
實例
創(chuàng)建兩個 shell 腳本文件。
test1.sh 代碼如下:
#!/bin/bash # author:W3Cschool教程 # url:m.hgci.cn url="http://m.hgci.cn"
test2.sh 代碼如下:
#!/bin/bash # author:W3Cschool教程 # url:m.hgci.cn #使用 . 號來引用test1.sh 文件 . ./test1.sh # 或者使用以下包含文件代碼 # source ./test1.sh echo "W3Cschool教程官網(wǎng)地址:$url"
接下來,我們?yōu)?test2.sh 添加可執(zhí)行權(quán)限并執(zhí)行:
$ chmod +x test2.sh $ ./test2.sh W3Cschool教程官網(wǎng)地址:http://m.hgci.cn
注:被包含的文件 test1.sh 不需要可執(zhí)行權(quán)限。
更多建議: