On Tue, Oct 27, 2026 at 07:38:01 +0100, john doe wrote:
> Now that  I have publicly humiliated myself, lets make it a learning
> moment!!! ;^)
> 
> What would be the correct way to populate an array programmatically?

Depends on what you're putting in it.  If it's just a fixed set of
strings, simply write them out:

    a=( zero one two three )
    b=( {0..9} )
    c=(
        "The first element is a sentence."
        "So is the second element."
        "I'm not."              # ???
        "Yes, you are!"
    )
    # Yes, you can put comments inside this format.

If it's filenames, use a glob (pathname expansion):

    d=( ~/wallpaper/* )

Remember that the glob characters, and in this case the tilde, are
supposed to be expanded by the shell, so they must not be quoted.  If
there's a separate part of the word that needs to be quoted, then
put the quotes only around that part:

    e=( "$cfgdir"/*.conf )

If the array is populated by the output of a program, then use the
readarray (a.k.a. mapfile) builtin, or a loop:

    readarray -t f < <(something that writes one element per line)

    readarray -d '' -t g < <(something that writes NUL-delimited elements)

    # This is what we used before readarray -d ''
    h=()
    while LC_ALL=C IFS= read -r -d '' file; do
        h+=( "$file" )
    done < <(find ... -print0)

*Do not* use this with a naive ls command.

    # Don't do this!
    readarray -t wrong < <(ls *.gif)

ls will often mangle filenames, and even if it doesn't, filenames that
contain newlines will break this.  If you want to load the filenames
from a directory non-recursively, use the glob syntax:

    i=( *.gif )

If you need to grab them recursively, use find with -print0:

    readarray -d '' -t j < <(find . -type f -name '*.gif' -print0)

Or you can use bash's globstar option:

    shopt -s globstar
    k=( **/*.gif )

If you need to get the filenames in an order that isn't what globbing
produces (e.g. sorted by mtime), GNU coreutils ls has special options
that can make this work.  I cover this at
<https://mywiki.wooledge.org/ParsingLs#Notes_on_GNU_coreutils_ls> and
I'll show the first example here:

    # Delete the 5 oldest files
    # in the current directory.
    readarray -t -d '' -n 5 sorted < <(ls --zero -tr)
    (( ${#sorted[@]} == 0 )) || rm -- "${sorted[@]}"

If your ls command doesn't have a --zero option, or a --quoting-style
option, then you can't use it to grab filenames programmatically.
GNU find with a fancy -printf option would be your next recourse.
There's an example on <https://mywiki.wooledge.org/BashProgramming/03>
(search for rlart) but it doesn't use arrays, and it's a bit beyond the
complexity limit for this email.

Reply via email to