• Willkommen im Linux Club - dem deutschsprachigen Supportforum für GNU/Linux. Registriere dich kostenlos, um alle Inhalte zu sehen und Fragen zu stellen.

[gelöst] bash-Arrays in while-Schleifen ?

abgdf

Guru
Hallo,

ich hab da mal 'ne Frage: Warum kann das Array in folgendem Beispiel die Werte nicht halten, während es es im zweiten kann ?

Also:
1. Beispiel:
Code:
#!/bin/bash

i=0

b='Eins\nzwei\ndrei\n'

echo -e $b | while read f
do
    a[$i]=$f
    echo $i: ${a[$i]}
    let "i += 1"
done

echo

for(( i=0;i<3;i++ ))
{
    echo $i: ${a[$i]}
}


2. Beispiel:
Code:
#!/bin/bash

i=0

while [ $i -lt 4 ]
do
    a[$i]=$i
    echo $i: ${a[$i]}
    let "i += 1"
done

echo

for(( i=0;i<3;i++ ))
{
    echo $i: ${a[$i]}
}

Hintergrund: Ich möchte gern wie im 1. Beispiel die Ausgabe von "find" in ein Array einlesen, schaff's aber einfach nicht ...

Viele Grüße
 
abgdf schrieb:
Warum kann das Array in folgendem Beispiel die Werte nicht halten, während es es im zweiten kann ?
Die Anweisung eines asynchronen Befehls (mit der Pipe) wird in einer Subshell ausgeführt.
man bash
A command invoked in this separate environment cannot affect the shell's execution environment.

Command substitution, commands grouped with parentheses, and asynchronous commands are invoked in a subshell environment that is a duplicate of
the shell environment, except that traps caught by the shell are reset to the values that the shell inherited from its parent at invocation.
Builtin commands that are invoked as part of a pipeline are also executed in a subshell environment. Changes made to the subshell environment
cannot affect the shell's execution environment.

Versuch mal:
Code:
#!/bin/bash 

find /foo -name "blah" -type f > /bar/results

while read f; do
  a[$i]=$f;
  echo $i: ${a[$i]};
  let "i += 1";
done < /bar/results;

echo 
 
for(( i=0;i<3;i++ )) { 
   echo $i: ${a[$i]};
};
 
Oben