12

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

5

3 Answers 3

15

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It works, but only for files. I would also like to store name of a directory to array (if there is any)
Just modify the if in the loop according to your needs, then.
8

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

Comments

2
array=($(ls /home/user/DIRECTORY))

Then

echo ${array[0]}

will equal to the first file in that directory.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.