Convert ls Output Into an Array

8.6k views Asked by At

I want to put the output of an ls into an array so I can loop through it and eventually use a entry the user will specify.

What I did is the following

SETUPS="$(ls)"
IFS=$' ' read -rd '' setup <<<"$SETUPS"

when I run echo $setup[0] it will already show me all the files that are present
while I should be able to run echo $setup[0] and only get the first entry.

Could anyone tell me what I'm doing wrong here?

I already tried SETUPS="$(ls -1)" to seperate it with IFS=$'\n' read -rd '' setup <<<"$SETUPS" but that didn't work either.

Right now I'm looping through it like this

n=0
for i in `echo ${setup} | tr "," " "` 
   do
   n=$((n+1))
   echo $n". $i"
done

which works to echo every entry with a number in front of it but I can't possibly select an entry out of there since every value seems to be stored as 1 value

2

There are 2 answers

0
Eric Renouf On BEST ANSWER

If you want to get all the files in this directory in an array you can use globbing:

files=(*)
printf '%s\n' "${files[@]}"

will store all the files matched by the glob in the array files and then you can print them with printf if you so desire, or do whatever else you want with looping over the array.

n=0
for current in "${files[@]}"; do
    n=((n+1))
    printf '%s %s\n' "$n" "$current"
done

You don't even need to store it in an array in the middle if you don't need it for some other purpose:

for current in *; do

works just fine

3
Inian On

See, why not parse output of ls, but rather use a proper while loop with process-substitution (<()).

#!/bin/bash

while IFS= read -r -d '' file
do
    printf "%s\n" "${file#*/}" 
done < <(find . -maxdepth 1 -mindepth 1 -type f -print0)

(or) if you are interested in storing the folder contents in an array

fileContents=()
while IFS= read -r -d '' file
do
    fileContents+=("${file#*/}") 
done < <(find . -maxdepth 1 -mindepth 1 -type f -print0)

printf "%s\n" "${fileContents[@]}"