类似于C/C++中的include
操作,bash
也可以引入其他文件中的代码。
source
命令(从 C Shell 而来)是bash shell
的内置命令。点命令,就是一个点符号,(从Bourne Shell
而来)是source
的另一名称。- 这两个命令都以一个脚本为参数,该脚本中的内容将在当前shell的环境中执行,即不会启动一个新的子进程。所有在脚本中设置的变量将成为当前Shell的一部分。
语法格式:
. filename # 注意点和文件名之间有一个空格
或
source filename
示例
创建test1.sh
,内容为:
#! /bin/bash
name=yxc # 定义变量name
然后创建test2.sh
,内容为:
#! /bin/bash
source test1.sh # 或 . test1.sh
# 也可以加绝对路径。
echo My name is: $name # 可以使用test1.sh中的变量
执行命令:
acs@9e0ebfcd82d7:~$ chmod +x test2.sh
acs@9e0ebfcd82d7:~$ ./test2.sh
My name is: yxc