Skip to content

Instantly share code, notes, and snippets.

@azerum
Created December 12, 2025 09:03
Show Gist options
  • Select an option

  • Save azerum/67b8087a2996f99f42205d5fbc68b6e2 to your computer and use it in GitHub Desktop.

Select an option

Save azerum/67b8087a2996f99f42205d5fbc68b6e2 to your computer and use it in GitHub Desktop.
Automatic `nvm use` on cd'ing into directory for macOS zsh
# Generated by ChatGPT
# Keep track of last used .nvmrc path
typeset -g NVM_LAST_USED=""
# Function to find closest .nvmrc in current dir or above
function nvm_find_rc() {
local dir="$PWD"
while [[ "$dir" != "/" ]]; do
if [[ -f "$dir/.nvmrc" ]]; then
# Print full absolute path
echo "$(readlink -f "$dir/.nvmrc")"
return
fi
dir="${dir:h}" # zsh shorthand for parent dir
done
}
# Hook for directory changes
function nvm_auto_use() {
local rc
rc=$(nvm_find_rc)
# Skip if no .nvmrc
[[ -z "$rc" ]] && return
# Skip if same as last used
[[ "$rc" == "$NVM_LAST_USED" ]] && return
# Use the version in the nearest .nvmrc
echo "nvm using $(cat "$rc") from $rc"
nvm use
NVM_LAST_USED="$rc"
}
# Register hook
autoload -Uz add-zsh-hook
add-zsh-hook chpwd nvm_auto_use
# Also run on initial shell start
nvm_auto_use
@azerum
Copy link
Author

azerum commented Dec 12, 2025

Recommended, clean way to use:

  1. Add file to e.g. ~/dotfiles/auto-nvmrc.sh
  2. Add line source ~/dotfiles/auto-nvmrc.sh to ~/.zshrc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment