Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

source multiple files in .zshrc with wildcard

I use z shell via "oh my zsh". I'd like to source multiple alias files from within my .zshrc file so I can keep things well organized. I've prefixed the alias files with .alias_ so I can wildcard load them. But, a call to source ~/.alias_* only loads the first file. How can I script it to source multiple files?

Filename examples: .alias_git, .alias_local, .alias_server...

like image 830
cborgia Avatar asked Feb 03 '13 22:02

cborgia


2 Answers

Option 1

You could use a for loop:

for file in ~/.alias_*; do
    source "$file"
done

Option 2

The other option is to build an array of all the files you want to source and then iterate over the array using a for loop.

typeset -a aliases

aliases+="~/.alias_foo"
aliases+="~/.aliases_bar"
# etc...

for file in $aliases[@]; do
    if [[ -a "$file" ]]; then
        source "$file"
    fi
done

This can actually be quite effective in making a well organized zshrc setup.

like image 193
cyfur01 Avatar answered Sep 22 '22 23:09

cyfur01


An even more ZSH-specific way (requires setopt EXTENDED_GLOB):

alias_src=(
.alias_git
.alias_local
.alias_server
)
for f ($^alias_src(.N)) source $f
unset alias_src

The prefix ^ has the effect of applying the subsequent glob modifiers to every element of the array separately.

The trailing (.N) has the following effect:

  • .: only match files
  • N: temporarily setopt NULL_GLOB, which means that only those elements of the array that actually exist remain in the array
like image 22
simonair Avatar answered Sep 21 '22 23:09

simonair