有人可以向我解释一下这是怎么回事吗?
脚本:
#!/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
输出:
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:
预期的:
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
本质上,在循环结束时while
,WINS
数组以某种方式被重置,我不知道为什么。 bash 中是否有一些我不知道的奇怪的作用域?
答案1
管道创建子 shell,这些子 shell 无法更改其上方进程中的值。尝试:
while read window; do
WINS=( ${WINS[@]} $window )
echo "Found window: $window; New size: ${#WINS[@]}"
done < <(wmctrl -l | grep -Ev " (${SKIP})" | cut -d \ -f 1)