codef0rmer codef0rmer - 5 months ago 8x
Bash Question

How to store directory files listing into an array?

I'm trying to store the files listing into an array and then loop through the array again.
Below is what I get when I run

ls -ls
command from the console.

total 40
36 -rwxrwxr-x 1 amit amit 36720 2012-03-31 12:19 1.txt
4 -rwxrwxr-x 1 amit amit 1318 2012-03-31 14:49 2.txt

The following bash script I've written to store the above data into a bash array.

ls -ls | while read line
array[ $i ]="$line"
(( i++ ))

But when I
echo $array
, I get nothing!

FYI, I run the script this way:

Mat Mat

Try with:

#! /bin/bash

while read line
    array[ $i ]="$line"        
    (( i++ ))
done < <(ls -ls)

echo ${array[1]}

In your version, the while runs in a subshell, the environment variables you modify in the loop are not visible outside it.

(Do keep in mind that parsing the output of ls is generally not a good idea at all.)