Comportamento variável bizarro em loops 'while' [duplicate]

1

Alguém pode me explicar o que está acontecendo aqui?

Script:

#!/bin/sh
SKIP="unity-launcher|unity-panel|unity-dash|Hud|XdndCollectionWindowImp|Desktop"
WINS=()
wmctrl -l | grep -Ev " (${SKIP})" | cut -d \  -f 1 | while read window; do
    WINS=( ${WINS[@]} $window )
    echo "Found window: $window; New size: ${#WINS[@]}"
done
echo "Total window count: ${#WINS[@]}"
echo "Window IDs:"
for i in "${WINS[@]}"; do
    echo "  $i"
done

Saída:

Found window: 0x0380000a; New size: 1
Found window: 0x038002ae; New size: 2
Found window: 0x03800a33; New size: 3
Found window: 0x03000001; New size: 4
Found window: 0x04c00004; New size: 5
Total window count: 0
Window IDs:

Esperado:

Found window: 0x0380000a; New size: 1
Found window: 0x038002ae; New size: 2
Found window: 0x03800a33; New size: 3
Found window: 0x03000001; New size: 4
Found window: 0x04c00004; New size: 5
Total window count: 5
Window IDs:
    0x0380000a
    0x038002ae
    0x03800a33
    0x03000001
    0x04c00004

Essencialmente, no final do ciclo while , a matriz WINS está sendo redefinida de alguma forma, e não tenho ideia do motivo. Existe alguma coisa esquisita no bash que eu não conheço?

    
por Fordi 04.08.2016 / 17:00

1 resposta

5

Os pipes criam subshells e essas subshells não podem alterar os valores nos processos acima deles. Experimente:

while read window; do
    WINS=( ${WINS[@]} $window )
    echo "Found window: $window; New size: ${#WINS[@]}"
done < <(wmctrl -l | grep -Ev " (${SKIP})" | cut -d \  -f 1)
    
por 04.08.2016 / 17:12