Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script - how to fill array?

Tags:

arrays

bash

ls

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

like image 426
user1926550 Avatar asked Apr 10 '13 17:04

user1926550


People also ask

How do I add elements to an array in bash?

To append element(s) to an array in Bash, use += operator.

How do you fill an array with arrays?

Using the fill() method The fill() method, fills the elements of an array with a static value from the specified start position to the specified end position. If no start or end positions are specified, the whole array is filled. One thing to keep in mind is that this method modifies the original/given array.

How do I echo an array in bash?

How to Echo a Bash Array? To echo an array, use the format echo ${Array[0]}. Array is your array name, and 0 is the index or the key if you are echoing an associative array. You can also use @ or * symbols instead of an index to print the entire array.


1 Answers

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.

like image 131
Daniel Kamil Kozar Avatar answered Nov 20 '22 10:11

Daniel Kamil Kozar