How to store directory files listing into an array?

BashShell

Bash Problem Overview


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

Bash Solutions


Solution 1 - Bash

I'd use

files=(*)

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

Solution 2 - Bash

Try with:

#! /bin/bash

i=0
while read line
do
    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.)

Solution 3 - Bash

Here's a variant that lets you use a regex pattern for initial filtering, change the regex to be get the filtering you desire.

files=($(find -E . -type f -regex "^.*$"))
for item in ${files[*]}
do
  printf "   %s\n" $item
done

Solution 4 - Bash

This might work for you:

OIFS=$IFS; IFS=$'\n'; array=($(ls -ls)); IFS=$OIFS; echo "${array[1]}"

Solution 5 - Bash

Running any shell command inside $(...) will help to store the output in a variable. So using that we can convert the files to array with IFS.

IFS=' ' read -r -a array <<< $(ls /path/to/dir)

Solution 6 - Bash

You may be tempted to use (*) but what if a directory contains the * character? It's very difficult to handle special characters in filenames correctly.

You can use ls -ls. However, it fails to handle newline characters.

# Store la -ls as an array
readarray -t files <<< $(ls -ls)
for (( i=1; i<${#files[@]}; i++ ))
{
    # Convert current line to an array
	line=(${files[$i]})
    # Get the filename, joining it together any spaces
	fileName=${line[@]:9}
	echo $fileName
}

If all you want is the file name, then just use ls:

for fileName in $(ls); do
	echo $fileName
done

See this article or this this post for more information about some of the difficulties of dealing with special characters in file names.

Solution 7 - Bash

Isn't these 2 code lines, either using scandir or including the dir pull in the declaration line, supposed to work?

src_dir="/3T/data/MySQL";
# src_ray=scandir($src_dir);
declare -a src_ray ${src_dir/*.sql}
printf ( $src_ray );

Solution 8 - Bash

simply you can use this below for loop

declare -a arr
for file in *.txt
do
    arr=(${arrPi[*]} "$file")
done

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questioncodef0rmerView Question on Stackoverflow
Solution 1 - Bashglenn jackmanView Answer on Stackoverflow
Solution 2 - BashMatView Answer on Stackoverflow
Solution 3 - BashharschwareView Answer on Stackoverflow
Solution 4 - BashpotongView Answer on Stackoverflow
Solution 5 - BashrashokView Answer on Stackoverflow
Solution 6 - BashDan BrayView Answer on Stackoverflow
Solution 7 - BashOldManRiverView Answer on Stackoverflow
Solution 8 - BashRifwan JaleelView Answer on Stackoverflow