Created
December 12, 2025 09:03
-
-
Save azerum/67b8087a2996f99f42205d5fbc68b6e2 to your computer and use it in GitHub Desktop.
Automatic `nvm use` on cd'ing into directory for macOS zsh
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Recommended, clean way to use:
source ~/dotfiles/auto-nvmrc.shto ~/.zshrc