如何在父 shell 和子 shell 之间使用相同的 bash 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4391456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use the same bash variable between a parent shell and child shell
提问by toc777
I have a bash script similar to the following:
我有一个类似于以下的 bash 脚本:
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.
因为测试函数在子 shell 中运行,它不会影响正在运行的变量,我得到 0 回显到屏幕上。我需要子 shell 才能更改父 shell 变量,如何做到这一点?我试过出口,但无济于事。
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.
编辑感谢所有有用的答案,我想在后台运行此功能的原因是允许同时运行多个功能。我需要能够回调父脚本以告诉它所有功能何时完成。我一直在使用 pid 来做到这一点,但我不喜欢在循环中检查多个进程是否一直处于活动状态。
回答by Ron Ruble
You can't really. Each shell has a copy of the environment.
你真的不能。每个 shell 都有一个环境副本。
see Can a shell script set environment variables of the calling shell?
请参阅shell 脚本可以设置调用 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.
如果您只想有效地返回一个值,那么只需从函数中返回该值。
回答by mouviciel
Use aliases instead of functions. Or write a script with the function body and execute it with source.
使用别名而不是函数。或者用函数体写一个脚本并用source.
Both solutions avoid creating a sub-shell.
这两种解决方案都避免创建子外壳。

