October 6, 2006

HowTo: Pass variables from child to the parent

Filed under: tech — SiKing @ 11:20 am

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:


export MYVAR=value1

echo Initial: $MYVAR


echo Parent sees: $MYVAR

The child script is as follows:


# some code that modifies MYVAR, for example:


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:


# some code that modifies MYVAR, for example:


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.


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: Logo

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Create a free website or blog at

%d bloggers like this: