Home > Mobile >  Can I ensure that files selected by glob are in a particular order? Does 0_..., 1_... etc offer guar
Can I ensure that files selected by glob are in a particular order? Does 0_..., 1_... etc offer guar

Time:09-03

Gathering Knowledge on the internet I found this method of sourcing files to .zshrc to be very convenient for me. But my question is how would this for loop work and which files will be loaded 1st? For example of if I have a file called 0_alias.zsh and then 1_options.zsh. Will the file with name 0 be loaded 1st?

function src {
    [[ -r "$1" ]] && source "$1"
}

if [[ -d ~/.config/.zshell/func.d/ ]]; then
    for func in ~/.config/.zshell/func.d/*.zsh; do
        src "$func"
    done
    unset func
fi

CodePudding user response:

Zsh glob qualifiers include some options to control the sorting of the expanded filenames with the oX qualifier. Unfortunately, they only include things like sorting by file size or last-modified timestamp, not "version sort" where runs of digits are sorted numerically instead of lexicographically. However, parameter expansion flags do include such a sort option, so you can break it up into a couple of steps:

# Array of all expanded filenames
files=( ~/.config/.zshell/func.d/*.zsh )
# Iterate over all elements of the array in "version" order
for func in ${(n)files[@]}; do
    # stuff
done

This way you can get files in the desired order without having to resort to things like padding the names with leading 0's to get them to sort lexicographically.

Example:

$ files=( *.zsh )

# Default lexicographic order
$ print ${files[@]}
0_foo.zsh 123_quux.zsh 1_bar.zsh 23_baz.zsh

# "Version" order
$ print ${(n)files[@]}
0_foo.zsh 1_bar.zsh 23_baz.zsh 123_quux.zsh

But forget all that.

@Gairfowl mentioned a numeric_glob_sort option. Turns out that can be turned on just for a single expansion in the qualifiers - it's not with the oX sort options which is why I missed it earlier. So all you really need is:

for func in  ~/.config/.zshell/func.d/*.zsh(n); do
    # stuff
done
  • Related