开发者

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.


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.


Use aliases instead of functions. Or write a script with the function body and execute it with source.

Both solutions avoid creating a sub-shell.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜