Bash script - how to fill array?

user1926550 picture user1926550 · Apr 10, 2013 · Viewed 18.5k times · Source

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

Answer

Daniel Kamil Kozar picture Daniel Kamil Kozar · Apr 10, 2013

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.