简体   繁体   English

Bash:在函数调用之间共享变量

[英]Bash: share variables between functions calls

I have a script with some functions that is loaded in the beginning of other scrips to do the common work.我有一个带有一些函数的脚本,它在其他脚本的开头加载以执行常见的工作。 To avoid reprocess, I'm trying to create some kinda cache with some script scope variables.为了避免重新处理,我正在尝试使用一些脚本范围变量创建一些缓存 So this is my problem:所以这是我的问题:

supposing I have this scripts:假设我有这个脚本:

functions.sh函数.sh

#!/bin/bash
v_cache=

set_cache()
{
    v_cache=1
    echo 1
}
echo_cache()
{
    echo "v_cache=$v_cache"
}

test.sh测试文件

#!/bin/bash
. function.sh

var=`set_cache`
echo_cache

set_cache
echo_cache

Here is the output:这是输出:

$ ./test.sh 
v_cache=
1
v_cache=1

Calling a function in an attribution (either with ` func ` or $( func )) have different context than a simple call.在属性中调用函数(使用 ` func`或 $( func ))与简单调用具有不同的上下文。 I need to keep the same scope to all functions calls in the same script ( test.sh for example).我需要对同一脚本中的所有函数调用保持相同的范围(例如test.sh )。

For the example above, the output I was expecting is:对于上面的示例,我期望的输出是:

$ ./test.sh 
v_cache=1
1
v_cache=1

I tried to find some explanation for why it works this way, but can't found nothing.我试图找到一些解释为什么它会以这种方式工作,但什么也找不到。 I think `` trigger a new bash execution, completely independent.我认为``触发一个新的bash执行,完全独立。

There's a way to share a variable through all functions calls?有没有办法通过所有函数调用共享变量? What are the alternatives to bypass this behaviour?绕过这种行为的替代方法是什么?

The "unexpected" behavior is because of subshell creation with `` or $() at this line. “意外”行为是因为在这一行使用 `` 或 $() 创建子shell。

var=`set_cache`

When the subshell kicks off, it creates it's own variable called v_cache, sets it to 1, and echo's 1 back to set var in the parent shell.当子 shell 启动时,它会创建自己的变量 v_cache,将其设置为 1,然后返回 1 以在父 shell 中设置 var。 Then the subshell exits, and you echo v_cache (of the oringal/parent shell), which is unset.然后子shell退出,你回显v_cache(oringal/parent shell),这是未设置的。

There are different trains of thought with function, from my background and languages, you should never use a function to change a global, you should instead have it return a value for the global.函数有不同的思路,从我的背景和语言来看,你不应该使用函数来改变全局,而应该让它为全局返回一个值。 In this case, change your var to v_cache.在这种情况下,将 var 更改为 v_cache。 Other people (who must have a different background than me) feel this is a short coming of bash.其他人(他们的背景肯定与我不同)认为这是 bash 的短暂到来。

If you call function.sh by ./function.sh in test.sh, a sub shell will be launched to run funtion.sh, so the variable value will not be kept in the shell which test.sh is running.如果在 test.sh 中通过 ./function.sh 调用 function.sh,则会启动一个子 shell 来运行 funtion.sh,因此变量值将不会保存在 test.sh 正在运行的 shell 中。

You should call function.sh by source ./function.sh to run them in the same shell.您应该通过source ./function.sh调用 function.sh 以在同一个 shell 中运行它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM