can anybody explain to me what the shell does in the two examples A) and B) below? It obviously behaves differently, but I can't find out why the output is different.

Example: Let's have a script in our current directory named bla.sh with only one command:
echo ${0##/*} hello

A)
Started as: ./bla.sh
gives: ./bla.sh hello

B)
Started as: . bla.sh
gives: -bash hello

Disclaimer: If this is some *nix-noob-triviality, please bear with me... :-|
Since I use this in a script, the second output (because of the "-" in front of the -bash) kills the command. Of course, a simple -- before the ${...} helped, but I would love to understand what causes the output in the first place.
I love bash. And vi[m]. But I digress... :-)

link|improve this question
feedback

1 Answer

up vote 12 down vote accepted

This command looks for an executable (either binary or script) named bla.sh in the current directory, then runs it as a normal program:

./bla.sh

It doesn't matter if bla.sh is a bash script, a perl or python one, or a compiled binary.


And this command calls the bash builtin command source (which has this confusing alias .), and reads the contents of bla.sh as if they were typed by you:

. bla.sh

The above is equivalent to:

source bla.sh

This of course only works when bla.sh contains commands for the bash shell (if that's the one you are currently using), it won't work for perl scripts or anything else.

(This is explained in help . and help source too.)


Usually it is best to use the ./bla.sh method. Only ~/.bashrc, ~/.profile and such files are usually sourced, because they are supposed to modify the current environment.

link|improve this answer
GREAT! Thanks a lot! – Wolf Sep 13 '09 at 12:36
2  
Moreover, if you change bash environment in bla.sh, these changes are taken into account after . bla.sh but not after ./bla.sh. this is because . bla.sh runs in the context of the current bash whereas ./bla.sh runs as a subprocess. – mouviciel Sep 15 '09 at 12:09
1  
See also mywiki.wooledge.org/BashFAQ/060 for some examples. Note that source is a bash alias for ., not the contrary and source won't work in other shells. – mrucci Apr 15 '10 at 6:43
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.