problemas de bash asignando a un índice de matriz en un bucle
Puedo hacer que esto funcione en ksh pero no en bash, lo que realmente me está volviendo loco. Con suerte es algo obvio que estoy pasando por alto.
Necesito ejecutar un comando externo donde cada línea de la salida se almacenará en un índice de matriz.
¿Parece que este ejemplo simplificado está configurando la matriz en el bucle correctamente, sin embargo, una vez que el bucle ha completado, esas asignaciones de matriz han desaparecido? ¿Es como si el bucle se tratara completamente como un shell externo?
junk.txt
this is a
test to see
if this works ok
testa.sh
#!/bin/bash
declare -i i=0
declare -a array
echo "Simple Test:"
array[0]="hello"
echo "array[0] = ${array[0]}"
echo -e "\nLoop through junk.txt:"
cat junk.txt | while read line
do
array[i]="$line"
echo "array[$i] = ${array[i]}"
let i++
done
echo -e "\nResults:"
echo " array[0] = ${array[0]}"
echo " Total in array = ${#array[*]}"
echo "The whole array:"
echo ${array[@]}
Salida
Simple Test:
array[0] = hello
Loop through junk.txt:
array[0] = this is a
array[1] = test to see
array[2] = if this works ok
Results:
array[0] = hello
Total in array = 1
The whole array:
hello
Entonces, mientras estamos en el bucle, asignamos la matriz [i] y el eco lo verifica. Pero después del bucle, he vuelto a la matriz [0] que contiene "hola" sin otros elementos.
Los mismos resultados en bash 3, 4 y diferentes plataformas.