Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the same bash variable between a parent shell and child shell

I have a bash script similar to the following:


function test
{
   running=$(( $running - 1 ))
}

running=0
test &
echo $running


Because the test function is run in a sub shell it doesn't affect the running variable and I get 0 echoed to the screen. I need the sub shell to be able to change the parent shells variables, how can this be done? I have tried export but to no avail.

EDIT Thanks for all the helpful answers, The reason I want to run this function in the background is to allow the running of multiple of functions simultaneously. I need to be able to call back to the parent script to tell it when all the functions are finished. I had been using pids to do this but I don't like having to check if multiple processes are alive constantly in a loop.

like image 814
toc777 Avatar asked Dec 08 '10 19:12

toc777


1 Answers

You can't really. Each shell has a copy of the environment.

see Can a shell script set environment variables of the calling shell?

But for what you are doing in your example, try this as your script:

#!/bin/bash

function testSO
{    
    running=$(( $running - 1 ));
    return $running;
}

and invoke it as:

running=$(testSO)

If you only want to effectively return a value, then just return the value from the function.

like image 167
Ron Ruble Avatar answered Oct 18 '22 04:10

Ron Ruble