spring cc
spring cc

Reputation: 1027

Why is $0 different between `sh myscript` and `source myscript`?

I have a very simple shell scripts name test.sh:

[mylinux ~]$ cat test.sh
echo "a"
echo "${0}"

However, when I source it and sh it, the results are quite different:

[mylinux ~]$ sh test.sh 
a
test.sh
[mylinux ~]$ source test.sh 
array : x, y
0,x
1,x

I can't understand the results of source test.sh, and, after I changed the name of test.sh, the results changed also:

[mylinux ~]$ mv test.sh a.sh
[mylinux ~]$ source a.sh 
a
-bash

How can I understand this phenomenon?

BTW, the second strange results only exits in one of my remote linux session, in my local linux system, everything works fine. So for sure it's related to the environment, and what I can do to find the fundamental reason?

I found the real problem, that is, even if their is no such a file test.sh, I can even perform source test.sh to get the results:

[mylinux ~]$ rm test.sh 
[mylinux ~]$ source test.sh
array : x, y
0,x
1,x

This is quite strange for me...

Upvotes: 5

Views: 210

Answers (2)

chepner
chepner

Reputation: 531065

source performs path lookup on its argument if the argument doesn't contain any / characters, so while sh test.sh and source ./test.sh are guaranteed to be running code from a file in the current directory, source test.sh may be running a different script entirely. source test.sh will only run ./test.sh if it doesn't find test.sh in your PATH first.

Upvotes: 3

Jack
Jack

Reputation: 6158

When you run source test.sh, a new shell is not created, so the program, ${0}, is bash. When you run sh test.sh, bash creates a new shell, and sets ${0} to the name of the script.

Upvotes: 2

Related Questions