SiKing

October 6, 2006

HowTo: Pass variables from child to the parent

Filed under: tech — SiKing @ 11:20 am
Tags:

OK, so it’s Friday, and I am feeling geek-ish again. I have finally gotten an answer to a dilemma that I had for a little while. Here is some more of my wisdom, and I use that term loosely here!

One of the annoying limitations (features?) of bash is that it cannot pass environment variable values from a child process to a parent process. Luckily, just as with everything else in computers, there are ways around this. Following is one possible solution, which IMHO is one of cleanest available.

The scenario

You have a parent script, which calls a child process like so:

#!/usr/bin/bash

export MYVAR=value1

echo Initial: $MYVAR

my_child

echo Parent sees: $MYVAR

The child script is as follows:

#!/usr/bin/bash

# some code that modifies MYVAR, for example:

MYVAR=value2

Running the above parent script will produce the following output:

Initial: value1

Parent sees: value1

What you were hoping for is that the second line would read “value2”. Even export MYVAR=value2 in the child script will not change anything.

The fix

What you need is for the parent to source the child. The immediate conclusion is to source my_child from the parent. While this will work for the above (simplistic) example, you could run into a lot of trouble if other variables are introduced into the mix!

One solution is for the child to pass the value back through stdout. On line 4 of the above child script, add a print statement, so that the new child script becomes:

#!/usr/bin/bash

# some code that modifies MYVAR, for example:

MYVAR=value2

printf "MYVAR=${MYVAR}\n"

Now, from your parent, instead of just simply calling the child script, you use the eval command like so: eval `my_child`; note the back-ticks to first run the child script. The command my_child is executed first, and then eval takes it’s output and creates a new command out of that which gets executed next. This time you get the desired result.

Initial: value1

Parent sees: value2

The added benefit of this method, in case you missed it, is that almost all languages have some sort of a print statement. This means that the above child script could have been written in any language not just bash.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: