1834

9 分钟

#Bash 的 source 命令

source FILENAME [ARGUMENTS]

功能

在当前 Shell 中执行脚本文件。

Bash 直接执行脚本文件时,会创建一个新的 Shell。这会导致某些操作无法进行(例如设置原 Shell 的环境变量),必须使用 source 命令。

类型

Bash 内置命令。

参数

  • FILENAME - 要执行的脚本文件
  • ARGUMENTS - 脚本文件的实参列表

#示例

$ cat > env.sh << 'EOF' # 写文件,遇到 EOF 时结束 export DATABASE_URL="postgresql://user:pass@localhost:5432/mydb" export API_KEY="abc123def456" export DEBUG="true" EOF $ echo $DATABASE_URL $API_KEY $DEBUG # 查看环境变量,此时是空的 $ chmod +x env.sh # 授予 env.sh 执行权限 $ ./env.sh # 直接执行会创建新的 Shell,因此设置的是新 Shell 的环境变量 $ echo $DATABASE_URL $API_KEY $DEBUG # 查看环境变量,仍然是空的 $ source ./env.sh # 通过 source 命令在当前 Shell 执行,可以设置当前 Shell 的环境变量 $ echo $DATABASE_URL $API_KEY $DEBUG # 查看环境变量 postgresql://user:pass@localhost:5432/mydb abc123def456 true
  • 直接执行脚本文件会创建新的 Shell,因此设置的是新 Shell 的环境变量
  • 通过 source 命令可以在当前 Shell 执行脚本文件,因此可以设置当前 Shell 的环境变量

#手册

NAME source - Execute commands from a file in the current shell. SYNOPSIS source FILENAME [ARGUMENTS] DESCRIPTION Execute commands from a file in the current shell. Read and execute commands from FILENAME in the current shell. The entries in $PATH are used to find the directory containing FILENAME. If any ARGUMENTS are supplied, they become the positional parameters when FILENAME is executed. Exit Status: Returns the status of the last command executed in FILENAME; fails if FILENAME cannot be read. SEE ALSO bash(1) IMPLEMENTATION GNU bash, version 5.0.17(1)-release (x86_64-redhat-linux-gnu) Copyright (C) 2019 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

创建于 2025/10/27

更新于 2025/10/27