我查阅资料的时候发现英文最普遍的解释是:
In Linux systems, source is a built-in shell command that reads and executes the file content in the current shell.
关键词:内置命令,在当前的shell执行文件的内容
source
与 sh
(bash
/zsh
等) 的区别
最关键的区别是 sh
会建立一个子进程来执行文件中的内容,而source
不会新建进程,而是在当前shell里面执行。
因此,
sh filename
重新建立一个子shell,在子shell中执行脚本里面的语句,该子shell继承父shell的环境变量,但子shell新建的、改变的变量不会被带回父shell,除非使用export。
而source filename
因为不会新建进程,所以新建的变量等会保留下来。
验证
要验证也很简单,😏,在执行的文件里写入ps
命令,然后分别用两个命令执行即可。
vim hello.sh
,写入以下内容:
ps
然后如下图所示,执行并对比:
可以看到source
没有新建线程,sh(bash/zsh)
新建了一个线程执行。
参考文章:
- https://www.cnblogs.com/shuiche/p/9436126.html
- https://www.geeksforgeeks.org/source-command-in-linux-with-examples/