2010-02-25 10 views
10

Ecco cosa sto cercando. Quello che voglio è l'ultimo echo dire "uno due tre quattro test1 ..." mentre scorre. La sua non funziona; read line sta arrivando vuoto. C'è qualcosa di sottile qui o semplicemente non funzionerà?Posso leggere la riga da un heredoc in bash?

array=(one two three) 
echo ${array[@]} 
#one two three 
array=(${array[@]} four) 
echo ${array[@]} 
#one two three four 


while read line; do 
     array=(${array[@]} $line) 
     echo ${array[@]} 
done < <(echo <<EOM 
test1 
test2 
test3 
test4 
EOM 
) 
+0

'array + = ("quattro")' e 'array + = ("$ riga")' –

risposta

16

Io normalmente scrivere:

while read line 
do 
    array=(${array[@]} $line) 
    echo ${array[@]} 
done <<EOM 
test1 
test2 
test3 
test4 
EOM 

Oppure, ancora più probabile:

cat <<EOF | 
test1 
test2 
test3 
test4 
EOF 

while read line 
do 
    array=(${array[@]} $line) 
    echo ${array[@]} 
done 

(Si noti che la versione con un tubo non sarà necessariamente adatto in Bash The Bourne. shell eseguirà il ciclo while nella shell corrente, ma Bash lo eseguirà in una subshell, almeno per impostazione predefinita. Nella shell Bourne, le assegnazioni fatte nel ciclo sarebbero disponibili nella principale shell dopo il ciclo; a Bash, non lo sono. La prima versione imposta sempre la variabile di matrice quindi è disponibile per l'uso dopo il ciclo)

Si potrebbe anche usare:.

array+=($line) 

aggiungere alla matrice.

4

sostituire

done < <(echo <<EOM 

con

done < <(cat << EOM 

lavorato per me.

1

È possibile inserire il comando davanti, mentre invece:

(echo <<EOM 
test1 
test2 
test3 
test4 
EOM 
) | while read line; do 
     array=(${array[@]} $line) 
     echo ${array[@]} 
done 
+0

E come sha dice, il gatto è probabilmente più appropriato di eco qui. – hlovdal