Shell File Inclusion

Like other languages, Shell can also include external scripts. This makes it convenient to encapsulate some common code as an independent file.

The syntax format for Shell file inclusion is as follows:

. filename   # 注意点号(.)和文件名中间有一空格

或

source filename

Examples

Create two shell script files.

The code for test1.sh is as follows:

#!/bin/bash
# author:Example
# url:www.example.com

url="http://www.example.com"

The code for test2.sh is as follows:

#!/bin/bash
# author:Example
# url:www.example.com

#使用 . 号来引用test1.sh 文件
. ./test1.sh

# 或者使用以下包含文件代码
# source ./test1.sh

echo "Example官网地址:$url"

Next, we add executable permission to test2.sh and execute it:

$ chmod +x test2.sh 
$ ./test2.sh 
Example官网地址:http://www.example.com

Note:The included file test1.sh does not need executable permission.

Other Extensions