在参数为 bash 的函数中使用全局变量

Using global variables in functions with parameters in bash

我正在尝试从 bash 中的一个函数中获取一个 return 值,该函数修改了一个全局变量。 与没有参数的函数完美配合:

#!/bin/bash

tes=2
testfunction(){
        tes=3
        tes_str="string result"
        return 0
}
if output=testfunction; then
        echo "OK"
else
        echo "KO"
fi
echo $tes
echo $tes_str

但没有参数:

#!/bin/bash

tes=2
testfunction(){
        tes=3
        tes_str="string result"
        return 0
}
if output=$(testfunction "AA" "BB"); then
        echo "OK"
else
        echo "KO"
fi
echo $tes
echo $tes_str

因为bash,参数(“AA”或“BB”)是一个命令,我必须把它放在backets中(但是如果使用backets,不能修改全局变量)。 我该怎么做?我卡住了。 此致

为什么要使用output?只需删除它和 运行 函数。

if testfunction; then

备注:

  • output=testfunction 正在将 text testfunction 分配给变量 output.
  • output=$(testfunction) 将不起作用,因为 $(...) 运行 子外壳中的所有内容。