Felix
Felix

Reputation: 13

ZSH always requires to restart terminal in order to access alias

I have added several aliases to my .zshrc file and they ONLY work if I restart terminal or use the source ~/.zshrc If I just open terminal, then type the alias, it will not recognize it, until I call source ~/.zshrc

So I know it's not a problem with the alias I created, I just have to load up the .zshrc file every time I want to use them.

What is going on? How can I fix this?

Upvotes: 0

Views: 2700

Answers (1)

user1934428
user1934428

Reputation: 22291

Well, you don't expect that you only have to edit a file and then, by magic, all your current zsh instances somehow ingest the changes, do you?

From the zsh man page, section STARTUP/SHUTDOWN FILES :

if the shell is interactive, commands are read from /etc/zshrc and then $ZDOTDIR/.zshrc

($ZDOTDIR defaults to your $HOME). Hence, if you are in your terminal, you have three choices. Two of them you already found out (restart the terminal, source .zshrc manually). The third choice would be to just open a zsh subshell (by typing zsh).

Actually, there is a trick to do some "magic" in reading the file automatically: Zsh allows you to define a so-called precmd hook, which allows you to establish an arbitrary command to be executed just before a command prompt will be displayed. You could use it to source any file you like. If you want to use this feature, I strongly recommend against sourcing all of .zshrc. Sooner or later, you will have stuff in .zshrc that you don't want to be executed every time.

Instead, put your alias definitions into a separate file, say $HOME/.aliases, and in Zsh define the hook

function precmd {
  source $HOME/.aliases
}

If you later change the .aliases file, you would still have to type a Carriage Return in your shell, in order to provoke a new prompt to be written and the precmd to be executed, but this is less cumbersome than sourcing the file manually.

Upvotes: 0

Related Questions