Reputation: 6306
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
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 Pythondirenv
supports unloading environment variables when you quit from the specific dirdirenv
covers many shellsSimilar projects
Upvotes: 4
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
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