There are several ways to run a shell script in Linux: directly execute it (./scriptname, assuming it is executable), invoke the script with sh command or with source (dot) command. What’s the difference?

Let’s try the following example:

Open a shell and type
x=10 (Note that there’s no space between each character)
echo $x
This will create a variable x and set its value to 10. Then print out current value of x in current shell.

Next open text editor and paste the following lines to it and save it as test.sh.
#!/bin/sh
x=20
echo $x

Now use sh command to run the script by typing
sh test.sh

When sh runs the script, it will ignore the first line because it starts with #, which indicates comment. Then it will open another shell and run the following lines.

After running sh, let’s check x again by typing
echo $x
It will show 10 because x is modified in another shell. The x in this shell is not affected.

Now let’s make this file executable by typing
chmod u+x test.sh

Now execute the file
./test.sh

When executing a file, #! will be treated as special characters. The characters after #! indicates the path of interpreter for this script. In this case it executes sh to run the script. This equals using sh command to run the script.

After executing the script, let’s check x again:
echo $x
It will show 10 since sh is executed in another shell.

Now let’s type
. test.sh
Note that there’s a space between dot and filepath. The dot here equals “source”. So this actually is executing Linux source command and feed the test.sh file to it.

Just like sh, the source command will interpret the first line as comment and ignore it. Then it will execute the following lines in current shell.

Now let’s check x again. This time it will show 20. Because source ran the file in the same shell it is invoked. Therefore the value of x is change.

 

Reference:
http://bash.cyberciti.biz/guide/Shebang
http://bash.cyberciti.biz/guide/Source_command

silentlain 發表在 痞客邦 PIXNET 留言(0) 人氣()