Skip to content

Instantly share code, notes, and snippets.

@nkgentile
Created January 15, 2025 21:14
Show Gist options
  • Save nkgentile/613cf735f546df41a40cb8ac1ab36e43 to your computer and use it in GitHub Desktop.
Save nkgentile/613cf735f546df41a40cb8ac1ab36e43 to your computer and use it in GitHub Desktop.
Cleanup NVM-managed Node versions
# Add to .zshrc or similar, and run `cleanup-node-versions`
cleanup-node-versions() {
echo "Starting NVM cleanup..."
# Get all installed versions and sort them
local installed=($(nvm ls | grep -o "v[0-9]\+\.[0-9]\+\.[0-9]\+" | sort -V))
# Track versions to keep
local keep=()
local current_major=""
local latest_version=""
# Find latest version for each major release
for version in ${installed[@]}; do
local major=$(echo $version | cut -d. -f1)
if [[ $major != $current_major ]]; then
# New major version found
[[ -n $latest_version ]] && keep+=($latest_version)
current_major=$major
latest_version=$version
else
# Same major version, update if newer
latest_version=$version
fi
done
# Add the last latest version
[[ -n $latest_version ]] && keep+=($latest_version)
# Remove versions not in keep list
for version in ${installed[@]}; do
if [[ ! " ${keep[@]} " =~ " ${version} " ]]; then
echo "Removing $version..."
nvm uninstall $version
fi
done
echo "Cleanup complete. Remaining versions:"
nvm ls
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment