Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store directory files listing into an array?

Tags:

bash

shell

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.

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

But when I echo $array, I get nothing!

FYI, I run the script this way: ./bashscript.sh

like image 906
codef0rmer Avatar asked Mar 31 '12 09:03

codef0rmer


People also ask

How do you append to an array in bash?

To append element(s) to an array in Bash, use += operator. This operator takes array as left operand and the element(s) as right operand. The element(s) must be enclosed in parenthesis. We can specify one or more elements in the parenthesis to append to the given array.


1 Answers

I'd use

files=(*) 

And then if you need data about the file, such as size, use the stat command on each file.

like image 76
glenn jackman Avatar answered Oct 23 '22 12:10

glenn jackman