> 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 不需要可执行权限。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://toska.gitbook.io/sysadmin/shell-and-bash/16.shell-wen-jian-bao-han.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
