导入外部脚本

类似于C/C++中的include操作,bash也可以引入其他文件中的代码。

语法格式:

. 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中的变量

执行命令:

chmod +x test2.sh
./test2.sh

My name is: yxc

source 与直接执行的区别

source test1.sh(或 . test1.sh)是在当前 shell 进程内执行脚本,里面定义的变量、函数、cd 等对当前会话持续生效;而 ./test1.shbash test1.sh 会启动一个子进程执行,脚本结束后子进程消失,其中定义的变量对当前会话不可见。让配置生效的经典场景——修改 ~/.bashrc 后执行 source ~/.bashrc——正是利用了"在当前进程中执行"这一特性。

也因此要注意:source 会不加隔离地执行目标脚本中的所有代码,不要随意 source 来路不明的脚本。


项目分区导航文件重定向 ⬅️ | 21-导入外部脚本 | ➡️ ssh登入