使用结果填充数组时Bash,奇怪的变量范围

Jak*_*zik 17 arrays bash scope

我正在解析命令输出并将结果放入数组.

在退出内部循环之前工作正常 - 输出数组为空.

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[@]}"
}
Run Code Online (Sandbox Code Playgroud)

再次运行两个输出行时的输出:

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:
Run Code Online (Sandbox Code Playgroud)

我花了一个小时试图解决这个问题.请帮忙.;-)

Sha*_*hin 27

当您使用pipe(|)将命令输出传递给时while,您的while循环将在子shell中运行.当循环结束时,您的子shell终止,并且您的变量将不在循环外可用.

改为使用流程替换:

while read line; do
   # ...
done < <($glue_dir/get_keys $ip)
Run Code Online (Sandbox Code Playgroud)