9

Let's say I have this directory structure:

DIRECTORY:

.........a

.........b

.........c

.........d

What I want to do is: I want to store elements of a directory in an array

something like : array = ls /home/user/DIRECTORY

so that array[0] contains name of first file (that is 'a')

array[1] == 'b' etc.

Thanks for help

Trinimon
  • 13,839
  • 9
  • 44
  • 60
user1926550
  • 539
  • 5
  • 10
  • 18

3 Answers3

14

You can't simply do array = ls /home/user/DIRECTORY, because - even with proper syntax - it wouldn't give you an array, but a string that you would have to parse, and Parsing ls is punishable by law. You can, however, use built-in Bash constructs to achieve what you want :

#!/usr/bin/env bash

readonly YOUR_DIR="/home/daniel"

if [[ ! -d $YOUR_DIR ]]; then
    echo >&2 "$YOUR_DIR does not exist or is not a directory"
    exit 1
fi

OLD_PWD=$PWD
cd "$YOUR_DIR"

i=0
for file in *
do
    if [[ -f $file ]]; then
        array[$i]=$file
        i=$(($i+1))
    fi
done

cd "$OLD_PWD"
exit 0

This small script saves the names of all the regular files (which means no directories, links, sockets, and such) that can be found in $YOUR_DIR to the array called array.

Hope this helps.

Daniel Kamil Kozar
  • 18,476
  • 5
  • 50
  • 64
6

Option 1, a manual loop:

dirtolist=/home/user/DIRECTORY
shopt -s nullglob    # In case there aren't any files
contentsarray=()
for filepath in "$dirtolist"/*; do
    contentsarray+=("$(basename "$filepath")")
done
shopt -u nullglob    # Optional, restore default behavior for unmatched file globs

Option 2, using bash array trickery:

dirtolist=/home/user/DIRECTORY
shopt -s nullglob
contentspaths=("$dirtolist"/*)   # This makes an array of paths to the files
contentsarray=("${contentpaths[@]##*/}")  # This strips off the path portions, leaving just the filenames
shopt -u nullglob    # Optional, restore default behavior for unmatched file globs
Simon O'Doherty
  • 9,259
  • 3
  • 26
  • 54
Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151
2
array=($(ls /home/user/DIRECTORY))

Then

echo ${array[0]}

will equal to the first file in that directory.

chunky_pie
  • 41
  • 4