Unix Shell - Diff between sourcing a file and executing it

This is Interesting: Free IT Magazines  
Home > Archive > Unix Shell > November 2005 > Diff between sourcing a file and executing it





You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

Author Diff between sourcing a file and executing it
sclind@gmail.com

2005-11-22, 5:56 pm

Forgive this basic question, but I can't seem to find an answer
anywhere. My environment happens to be HPUX (and using ksh), but I
think the question is rather generic - what is the difference between
sourcing a file (eg, ". somefile") and executing it (eg, ./somefile)?

Most of my exposure to sourcing a file has been related to the rc
scripts that control system startup and shutdown. The file that is
sourced usually only has one or two lines that set a variable
controlling whether the calling script should continue to execute.

But there is some discussion taking place here regarding problems
sourcing profiles, and I guess I don't understand the difference
between sourcing the profile and actually executing it.

TIA,

Scott

Lars Kellogg-Stedman

2005-11-22, 5:56 pm

> But there is some discussion taking place here regarding problems
> sourcing profiles, and I guess I don't understand the difference
> between sourcing the profile and actually executing it.


If you *source* a file (with the "." or "source" command), the commands
in that file execute *in your current shell*. Variables set by the
script, changes in current directory, aliases, etc., will all persist in
your shell after the script has finished running.

This is why scripts in /etc/init.d often source in files -- either to
import variable definitions or common function definitions.

On the other hand, if you execute a script (by typing it's name, or "sh
<filename>", etc.), the script executes in a subshell. The script will
for the most part not effect your current environment -- when the script
finishes, you'll be back in the same state you were before it ran.

-- Lars

--
Lars Kellogg-Stedman <8273grkci8q8kgt@jetable.net>
This email address will expire on 2005-11-23.

sclind@gmail.com

2005-11-22, 5:56 pm

Lars -

Thanks! That makes it very clear to me.

Scott

Sponsored Links






Free braindumps | Software forum | Database administration forum

Copyright 2003 - 2008 webservertalk.com