Project-based .rc files with ZSH hooks
One of the undiscovered features you may find in your z-shell, probably more so when using a zsh framework such as oh-my-zsh or any other since in those cases, there is hardly any configuration left to do for you. I have found many gems previously untouched or unfamiliar while scouring through the zsh manual (however dreadfully indigestible it can be at times, especially for (shell) newbies) which I had no idea was possible.
This one is actually staring you right in the face when using something like zsh but I found I didn't give it any attention really until I got time to read up on stuff like how the prompt syntax works (which is a special case, of course, since it has to deal with stuff as invisible characters and the place they consume on the screen). When using a oh-my-zsh theme, you will notice it often (depending on the theme) recognizes when entering a Ruby project or a .git
enabled directory (repo).
This is due to the power of zsh hooks and one of the most potent ones is chpwd
which triggers each time - you guessed it right - you CHange Present Working Directory read when you cd a/path/somewhere
. It then doesn't take a genius to figure out you can easily make a .customrc
file which puts certain project specific environment variables on your shell. This avoids having to keep anything else (well not completely but can if you autoload the rest) in the ~/.zshrc
file than:
function chpwd {
DIRECTORY="$PWD"
while true
do
if [ -f './.env.rc' ]; then
source './.env.rc'
break
fi
if [ -f './env' ]; then
source './env'
break
fi
[ $PWD = '/' ] && break
cd -q ..
done
cd -q "$DIRECTORY"
}
And of course there are countless other variations imaginable how this could benefit you and any project mates without having to write a bootstrap script that pipes stdout export SOMETHING="nothing" >> .zshrc
and other of those shenanigan anti-patterns really. They take up precious memory resources on every shell spawning instance which is hardly required when you have a dozen or so projects to deal with: very costly in the end. This'll only export those to your shell environment when you actually visit the path which is usually when you intend to use functionality or do work stored inside the path files :)
Enjoy.
Written by Rob Jentzema
Related protips
2 Responses
This method for implement directory-based environment isn't good. You can see my plugin for ZSH: https://github.com/horosgrisa/autoenv
Yeah I figured the example should be changed. It's a direct copy paste from some source I can find anymore now, I should have referenced it anyway: sorry for that. Won't forget the next time and thanks for sharing anyway, I'll check out your implementation. Mind if I would use that or part, as an example use case?