当函数被撤销时,Bash全局变量没有改变
我想调用函数“B”并传递给它将调用的另一个函数名称(A1,A2等)。在这个函数中,通过哪个名字,我初始化了几个变量,但是我不能从“B”函数中读取它们。当函数被撤销时,Bash全局变量没有改变
function A1
{
echo "func 1"
result1="a1"
return 0
}
function A2
{
echo "func 2"
anotherResult="a2"
#..some other initialization
return 0
}
#...
function B
{
output=`$1` # $1 - function name
echo output=$output
echo result1=$result1 # <--- ERROR! result1 is empty!
}
B "A1" # main script runs function B and passes other function name
您的功能B不会调用A1。
请注意,output=$($1)
不会做你所期望的,因为$(...)
里面运行的任何内容都将在不同的进程中执行,当这个进程终止时,你设置的值将不再可用。
所以:
function B
{
output=\`$1\` # <-- this will not call the $1 but will only print it
output=`$1` # <-- ($($1) is a better style) - will call whatever
# inside $1, but in another process
$1 # <-- here is the missing call in the current process.
...
}
您可以使用重定向例如A1 > tmpfile
文件或命名管道,在通过文件系统的输出来获得,同时保持在当前进程的副作用:
function B
{
$1 > tempfile
read output < tempfile
echo output=$output
echo result1=$result1
}
会做你所期望的,但是会使用tempfile
你的文件 - 系统。
我需要该函数写入 output = func 1 result1 = a1 – 2011-04-11 13:48:29
当我调用output = \'$ 1 \'时 - 变量输出被初始化,但result1不是。 – 2011-04-11 13:51:02
而且我无法两次调用我的函数$ 1,因为它运行了大约一分钟。 – 2011-04-11 13:55:32
output ='$ 1'带反引号,没有反斜杠 – 2011-04-11 13:35:16
和B“A1”最后也是bash代码 – 2011-04-11 13:37:25
据此编辑。 – mouviciel 2011-04-11 14:23:48