1
votes

I am using Centos 6.5

I noticed some of our software wasn't working right and it was due to path errors and other environment setting being incorrect. I've run some test and (I am not an expert on Linux) when I use the export command to set an environment variable at the prompt, it works fine, such as

export PATH=$PATH:/opt/application

This will add the default path to the new addition just as expected.

But when I put the above command in a shell script and run the script, the path is NOT changed.

I have tried:

PATH=$PATH:/opt/application
export PATH

I tried:

PATH=${PATH}:/opt/application
export PATH

and

export PATH=$PATH:/opt/application

as well as

export PATH=${PATH}:/opt/application

But as soon as you do an echo or env command all you get back is the default PATH setting.

I cannot figure out why the prompt works but the shell script does not. I am running as root.

1

1 Answers

1
votes

Every program has its own environment. A program can change its environment, and it can cause those changes to be propagated to other programs it launches, but no program can change the environment of another running program.

The shell gives special prominence and access to its environment, but it must obey the same rules as any other program. When you run a shell script, that's a new program with (again) its own environment. Changes it makes to that environment are therefore not reflected in the environment of the parent shell instance.

What you can do with the shell, however, is instruct the current instance to read and process commands from a file instead of running them in a separate (sub)shell. This is how your shell configuration files (.bashrc, etc.) can be effective. In bash the command to do that is spelled .. You might use it like this:

. /opt/application/env.sh

If you want to do that in, say, a personal or global environment setup file, then you would be wise to protect it a bit:

test -r /opt/application/env.sh && . /opt/application/env.sh

to avoid processing of the setup file being prematurely aborted in the event that /opt/application/env.sh is removed or becomes inaccessible.