source script.sh 和 ./script.sh 执行脚本有什么区别?

这里有一个回答 What is the difference between executing a bash script and sourcing a bash script? 很详细,简单总结一下:

source script.sh 会在当前 shell 进程(当前环境上下文)执行,而./script.sh 则会新开一个 shell 进程来执行。举个例子:

假设有以下的脚本pid.sh :

#!/bin/sh
echo $$

$$会打印当前 shell进程的 pid

# 先手动执行一下,看输出结果
$ echo $$
25009

# 使用 source 的方法执行,
$ source pid.sh
25009


# 直接执行 pid.sh,
$ ./pid.sh
25011


# 重新使用 source 的方法,
$ source pid.sh
25009

可以看到,source pid.sh 每次执行的结果都一样,都是当前 shell 进程的 pid, 而 ./pid.sh 则每次都会新开一个 shell 进程。

note!!! ./script.sh. script.sh 是不一样的,. 其实是 source 的一个别名(alias)