[ILUG] ILUG Why Can't Shell Scripts Export Variables
Niall O Broin
niall at magicgoeshere.com
Wed Jan 31 11:48:02 GMT 2001
On Wed, Jan 31, 2001 at 02:51:04AM -0800, kosullivan_xlib Last Name wrote:
> #!/bin/sh
> export PATH=$HOME/bin:$PATH
> echo $PATH
> The path appears fine until you type the echo $PATH at the prompt where
> you get the path which you always had and none of the stuff in the script is
> in the path.
The export command sets a variable in such a way that CHILD processes
inherit its value. If you look at the transcript below, what export does
should be clear, and the difference between variable= and export variable=
niall at bagend:~ >confused_bash_user="kosullivan_xlib Last Name"
niall at bagend:~ >echo $confused_bash_user
kosullivan_xlib Last Name
niall at bagend:~ >bash
niall at bagend:~ >echo $confused_bash_user
niall at bagend:~ >exit
niall at bagend:~ >export confused_bash_user="kosullivan_xlib Last Name"
niall at bagend:~ >echo $confused_bash_user
kosullivan_xlib Last Name
niall at bagend:~ >bash
niall at bagend:~ >echo $confused_bash_user
kosullivan_xlib Last Name
niall at bagend:~ >exit
Now when you run a script and use export in the script any child processes
of that script will inherit that variable and its value but its parent
process e.g. your command shell will not. It's a long established Unix
principle that a child process cannot modify the parent's environment, and
it's quite deliberate. It can be got around by co-operating processes, but
not simply with a shell script as shown.
> Why is this aren't shell scripts just a collection of shell commands in a
> file and if it works at the prompt shouldn't it work in a script tes same
> way.
No, a shell script is NOT just a collection of shell commands in a file.
When a shell script runs, a new copy of the shell is invoked and it runs the
commands. You CAN do what you want by sourcing a collection of shell
commands in a file i.e. telling your current shell to run the list of
commands in a file with the source command i.e.
source command_list
and . acts as a shorthand for source so you can do
. command_list
With either of these, command_list will usually be searched for along the
path (except when it's not - read the source section of the bash man page)
so be careful that you don't write a script in your current directory with
the same name as something in your path - test is the classic example of
this. When command_list is found, the shell reads it line by line and
executes each line as a shell command. Note that command_list does not
need to be executable, nor does it need a #!/bin/bash line at the start.
Regards,
Niall
More information about the ILUG
mailing list