Skip to content
Advertisement

Shell script doesn’t work when I export a variable inside it

I have a script called installscript which needs a change to the PATH variable.

BuildScript file has the following code:

export PATH+=:foo/bar/
./installscript

Running ./BuildScript or source BuildScript fails with an error in installscript

I have made a NewScript and call BuildScript from it after exporting the PATH variable

export PATH+=:foo/bar/
./BuildScript.sh

running source NewScript works.

I don’t understand why running BuildScript alone won’t work.

Advertisement

Answer

That’s likely because you should not use relative directory paths in a PATH. A relative path is a pathname that doesn’t start with a slash. Try

PATH+=:/path/to/foo/bar    # Use absolute path starting with /

instead and don’t call scripts with ./script.sh but script.sh and let the system find the programs along the PATH.

Also note that executing a script cannot change the environment of the parent. If you need that, scripts must be sourced with . /path/to/script or source /path/to/script.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement