Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reload aliases on change automatically without closing the shell window

Tags:

zsh

I have my aliases stored in ~/.zsh_aliases and sourced in ~/.zshrc:

# Access custom aliases in the shell
[ -e "${HOME}/.zsh_aliases" ] && source "${HOME}/.zsh_aliases"

However, when changing the name of an alias, I have to always close the current shell window and open a new one for the change to become active.

Can Zsh automatically reload aliases on change to make them available without having to close the shell window?

like image 714
orschiro Avatar asked Oct 21 '25 02:10

orschiro


2 Answers

You do not actually need to close and reopen your terminal for that, just running source ~/.zsh_aliases (loads the new and changed aliases) or maybe exec zsh (replaces the current shell with a new one) would work, too.

If you really want to re-source ~/.zsh_aliases whenever it is modified, I would suggest adding the following to your ~/.zshrc:

# File containing aliases; 
ALIAS_FILE="${HOME}/.zsh_aliases

reload_aliases () {
    # do nothing if there is no $ALIAS_FILE
    [[ -e ALIAS_FILE ]] || return 1
    # check if $ALIAS_FILE has been modified since last reload
    # the modifier `(:A)` resolves any symbolic links
    if [[ $LAST_ALIAS_RELOAD < $(stat -c %Y ${ALIAS_FILE}(:A)) ]]; then
        # remove all aliases; optional!
        # only do this if all of your aliases are defined in $ALIAS_FILE
        # also affects aliases defined on the command line
        unalias -m '*'
        # load aliases
        source $ALIAS_FILE
        # update date of last reload
        LAST_ALIAS_RELOAD=$(date +%s)
    fi
}

# make reload_aliases to be run before each prompt
autoload -Uz add-zsh-hook
add-zsh-hook precmd reload_aliases

Note, that any changes will only be available on a new prompt. That means, if you modify ~/.zsh_aliases, you need to press at least Enter once in the all terminals for the changes to take effect.

like image 145
Adaephon Avatar answered Oct 24 '25 19:10

Adaephon


I use an alias, thusly: -

alias vialias='vi ~/.oh-my-zsh/custom/alias.zsh ; source ~/.oh-my-zsh/custom/alias.zsh'

When I run vialias, I edit my aliases, then when I leave vi, the change(s) take effect.

like image 36
furriephillips Avatar answered Oct 24 '25 18:10

furriephillips



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!