本文介绍了填充阵列时猛砸,怪异的变量范围与效果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我解析命令的输出,并把结果存入数组中。
I am parsing command output and putting results into array.
运行正常,直到退出内环 - 输出数组是空的。
Works fine until exiting the inner loop - output array is empty.
declare -a KEYS
#-----------------------------------------------------------------------------#
get_keys()
{
# this extracts key NAMES from log in format "timestamp keycode"
$glue_dir/get_keys $ip | while read line; do
echo line: $line
set -- $line # $1 timestamp $2 keycode
echo 1: $1 2: $2
key=(`egrep "\\s$2$" "$glue_dir/keycodes"`) # tested for matching '40' against 401, 402 etc
set -- $key # $1 key name $2 keycode
KEYS+=("$1")
echo key $1
echo KEYS inside loop: "${KEYS[@]}"
done
echo KEYS outside loop: "${KEYS[@]}"
}
在运行agains两条输出线路的输出:
The output when run agains two output lines:
line: 1270899320451 38
1: 1270899320451 2: 38
key UP
KEYS inside loop: UP
line: 1270899320956 40
1: 1270899320956 2: 40
key DOWN
KEYS inside loop: UP DOWN
KEYS outside loop:
我花了一个小时试图弄清楚这一点。请帮忙。 ; - )
I spent an hour trying to figure this out. Please help. ;-)
推荐答案
当您使用管道( |
)到命令的输出传递到而
,您,而
循环在子shell中运行。当循环结束时,你的子shell终止和你的变量将无法使用你的循环之外。
When you use a pipe (|
) to pass your command output to while
, your while
loop runs in a subshell. When the loop ends, your subshell terminates and your variables will not be available outside your loop.
使用来代替:
while read line; do
# ...
done < <($glue_dir/get_keys $ip)
这篇关于填充阵列时猛砸,怪异的变量范围与效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!