【发布时间】:2011-05-14 12:48:31
【问题描述】:
这是一个 shell 脚本:
globvar=0
function myfunc {
let globvar=globvar+1
echo "myfunc: $globvar"
}
myfunc
echo "something" | myfunc
echo "Global: $globvar"
调用时,它会打印出以下内容:
$ sh zzz.sh
myfunc: 1
myfunc: 2
Global: 1
$ bash zzz.sh
myfunc: 1
myfunc: 2
Global: 1
$ zsh zzz.sh
myfunc: 1
myfunc: 2
Global: 2
问题是:为什么会发生这种情况,什么行为是正确的?
P.S.我有一种奇怪的感觉,管道后面的函数是在一个分叉的shell中调用的......那么,有一个简单的解决方法吗?
P.P.S. 这个函数是一个简单的测试包装器。它运行测试应用程序并分析其输出。然后它增加 $PASSED 或 $FAILED 变量。最后,您会在全局变量中获得一些通过/失败的测试。用法是这样的:
test-util << EOF | myfunc
input for test #1
EOF
test-util << EOF | myfunc
input for test #2
EOF
echo "Passed: $PASSED, failed: $FAILED"
【问题讨论】:
-
好吧,在我看来 $globvar 不是局部变量,因为在没有管道的情况下调用 myfunc() 可以很好地增加全局变量 $globvar。问题是通过管道调用函数在 bash/sh 中不起作用。
标签: bash unix global increment