Linux shell引入外部文件

很多编程语言中都存在导入外部包或者外部文件的用法,比如import语句,include语句等等。

在Linux shell中也有类似的用法,导入格式:

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

或

source filename

创建两个 shell 脚本文件。

test1.sh 代码如下:

#!/bin/bash

url="http://www.catroom.com.cn/"

test2.sh 代码如下:

#!/bin/bash

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

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

echo "IT懒猫社区地址:$url"

接下来,我们为 test2.sh 添加可执行权限并执行:

$ chmod +x test2.sh
$ ./test2.sh

输出内容:
IT懒猫社区地址:http://www.catroom.com.cn

注意:被包含的文件 test1.sh 不需要可执行权限。