bash 导出不起作用(从调用函数以获取其回声)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7801108/
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
Export not working (from a function called to get its echo)
提问by robert
I have a code like this:
我有一个这样的代码:
#!/usr/bin/env bash
test_this(){
export ABC="ABC"
echo "some output"
}
final_output="the otput is $(test_this)"
echo "$ABC"
Unfortunately the variable ABCis not being set.
不幸的是,变量ABC没有被设置。
I have to call test_thislike that, since in my real program I give some arguments to it, it performs various complicated operations calling various other functions, which on the way export this or that (basing on those arguments), and at the end some output string is assembled to be returned. Calling it two times, once to get exports and once for the output string would be bad.
我必须这样调用test_this,因为在我的真实程序中我给它一些参数,它执行各种复杂的操作,调用各种其他函数,在导出这个或那个(基于这些参数)的路上,最后一些输出字符串被组装以返回。调用它两次,一次获取导出,一次获取输出字符串会很糟糕。
The question is: what can I do to have both the exports and the output string in place, but just by one call to such a function?
问题是:我该怎么做才能让导出和输出字符串都到位,但只需调用一次这样的函数?
The answer that I am happy with (thank you paxdiablo):
我很满意的答案(谢谢paxdiablo):
#!/usr/bin/env bash
test_this(){
export ABC="ABC"
export A_VERY_OBSCURE_NAME="some output"
}
test_this
final_output="the otput is $A_VERY_OBSCURE_NAME"
echo "$ABC" #works!
unset A_VERY_OBSCURE_NAME
采纳答案by paxdiablo
Yes, it isbeing set. Unfortunately it's being set in the sub-processthat is created by $()to run the test_thisfunction and has no effect on the parent process.
是的,它是被设置。不幸的是,它被设置在由运行该函数而创建的子进程中,并且对父进程没有影响。$()test_this
And calling it twice is probably the easiestway to do it, something like (using a "secret" parameter value to dictate behaviour if it needs to be different):
调用它两次可能是最简单的方法,例如(如果需要不同,则使用“秘密”参数值来指示行为):
#!/usr/bin/env bash
test_this(){
export ABC="ABC"
if [[ "" != "super_sekrit_sauce" ]] ; then
echo "some output"
fi
}
final_output="the output is $(test_this)"
echo "1:$ABC:$final_output"
test_this super_sekrit_sauce
echo "2:$ABC:$final_output"
which outputs:
输出:
1::the output is some output
2:ABC:the output is some output
If you reallyonly want to call it once, you could do something like:
如果你真的只想调用一次,你可以这样做:
#!/usr/bin/env bash
test_this(){
export ABC="ABC"
export OUTPUT="some output"
}
test_this
final_output="the output is ${OUTPUT}"
echo "1:$ABC:$final_output"
In other words, use the same method for extracting output as you did for the other information.
换句话说,使用与提取其他信息相同的方法来提取输出。

