Urgent.News

What's breaking now, across thousands of outlets.

Tech

Bring nvm as a Command to Your CLI: Demystifying the Shell Function

The problem Every frontend and full-stack developer has typed nvm install or nvm use into their terminal. It feels like any other CLI tool—just like git, docker, or npm. However, if you try to call nvm inside a Docker build, devcontainer, a CI/CD pipeline script, or a non-interactive shell, you are immediately met with the dreaded error: nvm: command not found. Understanding why this happens—and…

Developers frequently use nvm install or nvm use in their terminal, treating it like other CLI tools like git or npm. However, when they attempt to call nvm inside Docker build, devcontainer, CI/CD pipeline scripts, or non-interactive shells, they encounter the error "nvm: command not found." To understand why and how to properly expose nvm as a command, it's essential to understand its nature.

The misconception about nvm is that it's a standalone binary, similar to other CLI tools. In reality, nvm is not a standalone executable but a shell script function. This is because its primary function is to dynamically modify the parent shell's environment variables—specifically, it shifts paths in $PATH to point to different Node.js runtime versions. As such, a traditional binary running in an isolated subshell cannot modify the environment of the shell you are actively typing into.

To make nvm behave like a command, it must be loaded directly into the active shell session. This is achieved through sourcing. Developers can set NVM_DIR to $HOME/.nvm and source $NVM_DIR/nvm.sh directly into their shell process. By doing this, nvm becomes an active shell function, instantly available as a command.

The issue of missing nvm across different environments (like local machines, dotfile setups, and devcontainers) often arises due to the reliance of nvm on shell initialization files. When moving across different environments, this can break functionality. To address this:

Scenario A: For clean dotfiles and modular scripts, developers should isolate tool initializations into a dedicated script (e.g., $HOME/.scripts/external-tools.sh). Then, clean sourcing of this script from the shell profile can ensure nvm is available.

Scenario B: In Docker and devcontainer environments, the initial NVM initialization block may be dropped as containers start clean or override user profiles. To guarantee nvm availability for container users, the loader system-wide can be baked via /etc/bash.bashrc in the Dockerfile. By doing this, all users within the container will have nvm available.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

More from Wednesday 12 August →