Daisy Sophia Hollman
Daisy Sophia Hollman

Reputation: 6306

Source a file in zsh when entering a directory

Is there a way to source a particular file to set up the environment when entering a particular directory? Sort of like what rvm does, but more general.

Upvotes: 7

Views: 5510

Answers (3)

Simba
Simba

Reputation: 27758

What you want achieve is setting environment variables for a specific directory.

Compared with other tools designed for this, direnv is the best of them. One of the main benefit is that it supports unloading the environment variables when you exit from that directory.

direnv is an environment switcher for the shell. It knows how to hook into bash, zsh, tcsh, fish shell and elvish to load or unload environment variables depending on the current directory. This allows project-specific environment variables without cluttering the ~/.profile file.

What makes direnv distinct between other similar tools:

  • direnv is written in Go, faster compared with its counterpart written in Python
  • direnv supports unloading environment variables when you quit from the specific dir
  • direnv covers many shells

Similar projects

  • Environment Modules - one of the oldest (in a good way) environment-loading systems
  • autoenv - lightweight; doesn't support unloads; slow written in Python
  • zsh-autoenv - a feature-rich mixture of autoenv and smartcd: enter/leave events, nesting, stashing (Zsh-only).
  • asdf - a pure bash solution that has a plugin system

Upvotes: 4

Francisco
Francisco

Reputation: 4120

IMHO you should not use an alias for this but add a hook to any directory change:

autoload -U add-zsh-hook
load-local-conf() {
     # check file exists, is regular file and is readable:
     if [[ -f .source_me && -r .source_me ]]; then
       source .source_me
     fi
}
add-zsh-hook chpwd load-local-conf

This hook function will run on any directory change.

FWIW, should you wish to change dirs without trigering the hooks, use cd -q dirname

Upvotes: 24

Joe
Joe

Reputation: 28366

You could define a function that would perform the cd and then source a file. This function will try to source .source_me in the new directory, if it exists:

mycd () {
builtin cd $@
[ $? -eq 0 -a -f .source_me ] && source .source_me
}

Enable using the function with

alias cd=mycd

Upvotes: 1

Related Questions