<- Compound Commands | Job Control ->


Sourcing

When you call one script from another, the new script inherits the environment of the original script, just like running any other program in UNIX. Explaining what this means is out of the scope of this guide, but for the most part you can consider the environment to be the current working directory, open file descriptors, and environment variables, which you can view using the export command.

When the script that you ran (or any other program, for that matter) finishes executing, its environment is discarded. The environment of the first script will be same as it was before the second script was called, although of course some of bash's special parameters may have changed (such as the value of $?, the return value of the most recent command). This means, for example, you can't simply run a script to change your current working directory for you.



What you can do is to source the script, instead of running it as a child. You can do this using the . (dot) command:

. ./myscript   #runs the commands from the file myscript in this environment

This is often called dotting in a script. The . tells BASH to read the commands in ./myscript and run them in the current shell environment. Since the commands are run in the current shell, they can change the current shell's variables, working directory, open file descriptors, functions, etc.

Note that Bash has a second name for this command, source, but since this works identically to the . command, it's probably easier to just forget about it and use the . command, as that will work everywhere.


<- Compound Commands | Job Control ->

BashGuide/Sourcing (last edited 2012-11-30 17:38:59 by geirha)