Operating System - Linux
1827827 Members
1958 Online
109969 Solutions
New Discussion

Re: env variable from a script

 
SOLVED
Go to solution
Tonatiuh
Super Advisor

env variable from a script

How can I set an environment variable or alias, from inside a shell script?

I put the export command or the alias command but it does not works.
8 REPLIES 8
Rick Garland
Honored Contributor

Re: env variable from a script

Which shell is being used for the script? Different shells have different methods for setting env variables.

Example, csh vs bash
Tonatiuh
Super Advisor

Re: env variable from a script

Red Hat Enterprise Linux. Bash Shell
Rick Garland
Honored Contributor

Re: env variable from a script

This is a strange one.

If I try to set an env variable at command line it works. If I set an env from a '.' file it works. If I set an env variable from regular file it doesn't work

Rick Garland
Honored Contributor

Re: env variable from a script

My thought is that this is not suppose to work this way.

As stated, I make a file called 'test' and in this file I put 'CITY=LA;export CITY'. I cannot get the $CITY value.

If I rename this file to .test (same contents) and execute this file the env variable of `echo $CITY` is LA.

As stated, I do not believe this correct is how it works.

Stuart Browne
Honored Contributor
Solution

Re: env variable from a script

A child cannot set the environment of a parent.

In bash, you call an alias or a script.. it spawns off a sub-shell. The subshell protect's the parents environment space.

Most (if not all) linux based shells do this for security reasons. There are a few that don't (some versions of pdksh for instance).

To set the environment in the current shell, you either have to use '. <script>' commands, or set them manually.

What exactally are you trying to do?
One long-haired git at your service...
T G Manikandan
Honored Contributor

Re: env variable from a script

execute the env variable script using

. ./test
Tonatiuh
Super Advisor

Re: env variable from a script

This is what I want to do.

I want a script which can change several environment variables. And I want to invoke this scripts from everywhere I was in the directory hierarchie.

This is, wherever I am, I want to change several (defined) environment variables just typing a single word (command, name of the scripts, etc.).



Stuart Browne
Honored Contributor

Re: env variable from a script

Use a shell 'FUNCTION'.

In your profile/bash profile, set up the function do do what you require:

function name() {
command
command
command
}

And run 'name' when you need it. It changes the current shell's environment.

See 'man bash', the secion on 'FUNCTIONS'.
One long-haired git at your service...