You can see the difference by following this example:
(I assume the shell used is bash, if you use <insert you favorite shell here>, you can surely transfer this...)
create a file test-inc.sh with the following contents:
echo "The test variable is --$TESTVAR--"
make the file executable by you: chmod u+x test-inc.sh
now execute the following in a terminal (bash#
used to denote the prompt):
bash# TESTVAR="hello world"
bash# echo $TESTVAR
bash# . test-inc.sh
The test variable is --hello world--
The test variable is ----
so what happened?
First, we set a variable TESTVAR in the current shell to "hello world". The variable is not passed to subcommands (you had to use export TESTVAR
to do this).
On the next line, we printed the variable (the bash expanded its value and passed the value to the echo command, so technically, echo "hello world"
After that, we use the dot command to source our script file, that means the bash behaves as if the contents of the file was typed at that place where the dot command is written. So, technically a comment, an empty line and the third line (echo "The test variable is --$TESTVAR--") is executed. Of course, only the echo line is doing something and, as in the typed echo command before, the variable is expanded on the fly, so echo "The test variable is --hello world--"
In the next command, we execute the command test-inc.sh, that means:
- open the file
- interpret the shebang in the first line to find the program that should execute the script (here: /bin/bash)
- call the given program with the remaining contents as input:
- create a new bash shell with default variables etc. (see man bash for more)
- execute echo "The test variable is --$TESTVAR--". The variable is again substituted, but this time, the variable TESTVAR is not set (remember the missing export command above!). So now, the executed line will look like this: echo "The test variable is ----"
- the program (here: the "second" bash) ends and the next prompt for our first shell is shown again.
Hope to make it clear, If you think this is useful, feel free to copy this to a tutorial, but give me the url.