12. Shell 文件包含

  和其他语言一样,Shell 也可以包含外部脚本。这样可以很方便的封装一些公用的代码作为一个独立的文件。 Shell 文件包含的语法格式如下:

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

再次声明:

点号(.)和文件名中间有一个空格

实例

创建两个 shell 脚本文件。 test1.sh:

  1. #!/bin/bash
  2. # author: Asa Guo
  3. url="http://www.baidu.com"

test2.sh:

  1. #!/bin/bash
  2. # author: Asa Guo
  3. #方法1:使用点号(.)来引用test1.sh
  4. . ./test1.sh
  5. #方法2:使用source命令
  6. # source ./test1.sh
  7. echo "百度:$url"

运行test2.sh:

  1. $ chmod +x test2.sh
  2. $ ./test2.sh
  3. 百度:http://www.baidu.com

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