> For the complete documentation index, see [llms.txt](https://toska.gitbook.io/sysadmin/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://toska.gitbook.io/sysadmin/shell-and-bash/16.shell-wen-jian-bao-han.md).

# 16.Shell 文件包含

> ## Shell 文件包含 <a href="#shi-liu-shell-wen-jian-bao-han" id="shi-liu-shell-wen-jian-bao-han"></a>

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

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

或

```
1.source filename
```

实例\
创建两个 shell 脚本文件。\
test1.sh 代码如下：

```
1.#!/bin/bash
2.
3.
4.url="https://fatcatsk.github.io/"
```

test2.sh 代码如下：

```
1.#!/bin/bash
2.
3.#使用 . 号来引用test1.sh 文件
4.. ./test1.sh
5.
6.# 或者使用以下包含文件代码
7.# source ./test1.sh
8.
9.echo "shell学习笔记网地址：$url"
```

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

```
1.$ chmod +x test2.sh 
2.$ ./test2.sh 
3.shell学习笔记网地址：https://fatcatsk.github.io/
```

**实践1**

```
1.[root@localhost lcr]# vim  name.sh
2.[root@localhost lcr]# vim echo.sh
3.[root@localhost lcr]# chmod +x echo.sh
4.[root@localhost lcr]# ./echo.sh
5.LCR
```

* name.sh

```
1.#!/bin/bash
2.
3.myname=LCR
```

* echo.sh

```
1.#!/bin/bash
2.
3.. ./name.sh
4.
5.echo $myname
```

**实践2**

修改name.sh,增加一个输入

```
1.#!/bin/bash
2.
3.read myname
```

输出结果

```
1.[root@localhost lcr]# ./echo.sh
2.LCR
3.LCR
```

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