• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 310
  • Last Modified:

return env-variables back from a subshell

Hi!
using ksh:
I want to have a shellscript (or a subshell) returning me some env-variables set in the subshell - is this possible (I would call them "global" variables)?

thanks
witty
0
witty
Asked:
witty
1 Solution
 
s_franklinCommented:
That goes in the wrong direction I'm afraid. When you call a script directly, you're forking off a subprocess to interpret the script. This subprocess inherits a duplicate of your current environment variables - it can't manipulate your current ones directly. Rather it can manipulate its own copy.

What you can do is to source the script rather than execute it. i.e. if you have written "myscript.sh", if you type:

% testscript.sh

then you will launch a copy of whatever shell is required (either identified in the first line as #!/... or defaults to your current shell). This shell exists as its own process and the script will manipulate the env. vars of this subprocess.

However, you can do:

.. testscript.sh
or
source testscript.sh

If I remember correctly, the latter is how you do it in csh, but ksh acts like bash/sh and uses the ". ..." command.

This runs the script within the current shell and allows you to manipulate your current shell's environment variables.

Steve


0
 
s_franklinCommented:
Apologies on the previous submission - I typed one too many periods in the answer. You would type:

.. testscript.sh
or
source testscript.sh

For ksh, I believe the "." command is appropriate but if I'm wrong (haven't used it in a while), there aren't many alternatives :).

Steve
0
 
jlevieCommented:
The short answer is no, a subshell can't modify the environment of it's parent. The way the environment works is that each child process (an executable, a shell) inherits it's environment from it's parent, the parent being being whatever process launched the child. The inheritance is one way and the parent is (thankfully) unaware of anything that the child does to the environment.

The way to get env variables set in the parent shell from a script is to treat the script as a series of shell commands executed in the current shell. You can do this by executing the script like:

$ . script-file [args]

The current PATH is used searched to find the directory containging "script-file" and any arguments are passed to the script. For mor information see the man pages for ksh.
0
 
ahoffmannCommented:
it's as s_franklin already described, you need to source the shell script
I only know of another, very cumbersome, solution which might work depending on what you want to aquire.
0
 
wittyAuthor Commented:
that was what I neede!!

thanks to all of you!!

witty
0

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Tackle projects and never again get stuck behind a technical roadblock.
Join Now