开发者

What is difference between running the script as ./script.sh and . ./script.sh [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Difference between launching a script with ./script.sh and . ./sc开发者_StackOverflowript.sh

What is difference between running the script as ./script.sh and . ./script.sh


The sourced in (. ./script.sh) script runs in the same shell. Meaning that if it issues exit, your shell exits, if it sets environment variable, your shell is affected, etc. Normally, you want to run scripts in isolated subprocess (./script.sh).


The built-in command . causes the script to be run in the current process rather than in a subprocess. Using . allows your script to alter the environment of the current process. For example:

$ echo $FOO

$ cat script.sh
#!/bin/bash export FOO="this is foo" 
$ ./script.sh 
$ echo $FOO

$ . ./script.sh 
$ echo $FOO 
this is foo

Notice how in the second case, the environment variable FOO was created in the current process.

Here's a link to the bash man page section dealing with the . command:

http://www.gnu.org/software/bash/manual/bashref.html#index-g_t_002e-108


./script.sh runs the script. A new sub-shell is spawned and the script runs in it. Any changes to the environment made by the script will be local to the sub-shell. Once the subshell exits you won't see the changes made by it in the parent shell.

. ./script.sh sources the script that is it is run in the current shell so any environment changes made by the script will remain after the script exits.


Here's what makes it interesting:

$ cat script.sh
export HELLO=SIRE
$ ./script.sh
$ set | grep HELLO
$ . ./script.sh
$ set | grep HELLO
HELLO=SIRE

As you can see adding a "." makes the script run in the context of the current shell instead of as a separate process, and affects the environment of the current process, and everything else that comes with the current process.

This can be real fun if you do something like:

alias go=". /home/x/bin/navigate_to_location"

then just do:

go sources
go builddir
go games

and the current environment gets affected by the "." ;-)

So in short .. "." makes shell worth having :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜