[NBLUG/talk] bash script wonder

Ron Wickersham rjw at alembic.com
Tue Oct 5 02:39:33 PDT 2004


On Tue, 5 Oct 2004, Mitch Patenaude wrote:

> On Oct 4, 2004, at 11:56 PM, Micxz wrote:
> > When I run it I get:
> > micxz at neptune:~> ./test.sh
> > SuSE. I think
> > made it
> > /opt/kde3
> >
> > OK. Looks like worked right. both conditions are true. But I don't
> > know why after the script exits I get:
> >
> > micxz at neptune:~> env | grep KDEDIR
> > micxz at neptune:~> echo $KDEDIR
> >
> > nada' Were did my environment var go? Thanks in advance'
>
> This is a common mistake when writing shellscripts.  The script runs in
> a new instance of the shell which is a child of the interactive shell,
> and therefore the changes made to the environment don't propagate back
> up to the parent.  If you want the script to run in the current shell,
> then invoke it like so:
>
> foo at bar:~> . ./test.sh
>
> Or less cryptically:
>
> foo at bar:~> source test.sh
>
> Of course, if your intent is not to modify the environment of the
> currently running interactive shell, but only to set it up for this
> script and processes spawned by the script, then the technique you're
> using will work fine.
>
>    -- Mitch

to further amplify what Mitch wrote, export makes the environment variable
available to a child process (without it a child wouldn't see the value
you set in the script).

source goes the other way and causes the text in your file to be executed
in the current shell as if you typed the lines in one at a time
interactively (as opposed to creating a child process).   thus your
environment will be affected.

another thing to note is when using source the execute permissions don't
need to be set (and for that matter the first line of your file will be
interpreted as a comment, so you could have written the first line as
#!/bin/dogsh and it would still run with source).

-ron




More information about the talk mailing list