Question about the difference between "for" and "while" loop

dear all,

i got some questions about for/while loop when working on redirect command output to for/while loop.

take one for example :

in for loop :

allfiles=`find /var/log -maxdepth 1 -type f -mtime +5`
index=1
for ((i=0; i<${#allfiles[@]}; i++)); do
    echo "$index:${allfiles[$i]}"
    index=`expr $index + 1`
done

this will have the output something below, only the first one will have the $index variable:

# ./my_script.sh
1: /var/log/mcelog
/var/log/maillog.2
/var/log/spooler.2
/var/log/rpmpkgs.2
/var/log/boot.log.2
/var/log/anaconda.syslog

however, if i change to use "while" loop, then it's different:

index=1
find /var/log -maxdepth 1 -type f -mtime +5 |
while read line; do
      echo "$index: $line"
      index=`expr $index + 1`
done

the command output will look like below, every line will have
the $index variable in the beginning:

# ./my_script.sh
1: /var/log/mcelog
2: /var/log/maillog.2
3: /var/log/spooler.2
4: /var/log/rpmpkgs.2
5: /var/log/boot.log.2
6: /var/log/anaconda.syslog

Can anyone advise why the result from "for" and "while" isn't same??

Thanks.

Is it at all possible that allfiles is a multi-line string rather than an array of single line strings in your for loop?

Try the following:

allfiles=(`find /var/log -maxdepth 1 -type f -mtime +5`)

In the for loop you are not putting the files into an array, but rather into a string, therefore the loop is executed only once for "${allfiles[0]}" , which contains the entire list of files.

Use this instead:

allfiles=( $(find /var/log -maxdepth 1 -type f -mtime +5) )