【问题标题】:Bash functions returning values meanwhile altering global variablesBash 函数返回值同时改变全局变量
【发布时间】:2016-11-19 21:14:33
【问题描述】:

我只是在 bash 函数中苦苦挣扎,并试图返回字符串值,同时在函数内部修改了一些全局变量。一个例子:

MyGlobal="some value"

function ReturnAndAlter () {
  MyGlobal="changed global value"
  echo "Returned string"
}

str=$(ReturnAndAlter)
echo $str            # prints out 'Returned value' as expected
echo $MyGlobal       # prints out the initial value, not changed

这是因为 $(...)(如果使用 `...` 代替)会导致函数拥有自己的环境,因此全局变量永远不会受到影响。

我发现了一个非常肮脏的解决方法,将值返回到另一个全局变量并仅使用其名称调用该函数,但认为应该有一种更简洁的方法来做到这一点。

我的肮脏解决方案:

MyGlobal="some value"
ret_val=""

function ReturnAndAlter () {
  ret_val="Returned string"
  MyGlobal="changed value"
}

ReturnAndAlter            # call the bare function
str=$ret_val              # and assign using the auxiliary global ret_val 
echo $str
echo $MyGlobal            # Here both global variables are updated.

有什么新想法吗?调用我缺少的函数的某种方式?

【问题讨论】:

    标签: bash global-variables return-value


    【解决方案1】:

    设置全局变量是函数与调用它的 shell 直接通信的唯一方法。通过捕获标准输出来“返回”一个值的做法有点像 shell 语义所必需的一种 hack,它旨在使调用 other 程序变得容易,而不是让它变得容易外壳本身的东西。

    所以,别担心;不,你不会错过任何很酷的技巧。你正在做 shell 允许你做的事情。

    【讨论】:

      【解决方案2】:

      $(…)(命令扩展)在子 shell 中运行。
      当子shell关闭时,子shell内部的所有更改都会丢失。

      在函数中同时使用打印结果和更改变量通常是一个坏主意。要么制作所有变量,要么只使用 one 打印字符串。

      没有其他解决方案。

      【讨论】:

      • @SergioGarcíaGalán 很好,那么你可以使用它。
      • 最后我不得不重组我的整个脚本,这样现在就不需要这种功能了。很高兴它处于早期阶段:-D 谢谢大家!
      猜你喜欢
      • 2020-09-11
      • 1970-01-01
      • 1970-01-01
      • 2020-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-12
      相关资源
      最近更新 更多