为什么 `sh myscript` 和 `source myscript` 之间的 $0 不同?

spr*_* cc 5 unix linux bash shell

我有一个非常简单的 shell 脚本名称test.sh

[mylinux ~]$ cat test.sh
echo "a"
echo "${0}"
Run Code Online (Sandbox Code Playgroud)

然而,当我sourcesh它时,结果却截然不同:

[mylinux ~]$ sh test.sh 
a
test.sh
[mylinux ~]$ source test.sh 
array : x, y
0,x
1,x
Run Code Online (Sandbox Code Playgroud)

我无法理解 的结果source test.sh,并且在更改 的名称后test.sh,结果也发生了变化:

[mylinux ~]$ mv test.sh a.sh
[mylinux ~]$ source a.sh 
a
-bash
Run Code Online (Sandbox Code Playgroud)

我该如何理解这种现象呢?

顺便说一句,第二个奇怪的结果只存在于我的远程 Linux 会话之一中,在我的本地 Linux 系统中,一切正常。那么肯定和环境有关,我该怎么做才能找到根本原因呢?

我发现了真正的问题,那就是,即使他们没有这样的文件test.sh,我什至可以执行source test.sh以获得结果:

[mylinux ~]$ rm test.sh 
[mylinux ~]$ source test.sh
array : x, y
0,x
1,x
Run Code Online (Sandbox Code Playgroud)

这对我来说很奇怪......

che*_*ner 3

source如果参数不包含任何/字符,则对其参数执行路径查找,因此虽然sh test.shsource ./test.sh保证从当前目录中的文件运行代码,但source test.sh可能正在运行完全不同的脚本。仅当在您的第一个中找不到时source test.sh才会运行。./test.shtest.shPATH