Posted 10 days ago. Visible to the public. Repeats.

NVM: How to automatically switch version when changing directories

The Node Version Manager allows installing multiple NodeJS versions and switching between them.
By default, it does not automatically switch versions when entering a directory that holds a .nvmrc file.

The project's readme document offers a bash function which calls nvm use after each cd. In fact, it replaces cd in your bash.

I did not want to do that, but instead use the $PROMPT_COMMAND feature. So here is my take on it.
Note that it is much shorter, it probably does a few less smart things, but has been working great for me for a long while.
Also note that it compares .nvmrc file paths instead of comparing nvm current, so cding around subdirectories of your project should work without any noticable performance impact.

Put the following at the end of your ~/.bashrc (the first three lines might already be in there):

export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/" ] && \. "$NVM_DIR/" [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" find-up() { path=$(pwd) while [[ "$path" != "" && ! -e "$path/$1" ]]; do path=${path%/*} done echo "$path" } automatic-nvm-use() { NVM_PATH=$(find-up .nvmrc | tr -d '[:space:]') if [[ $NVM_PATH == $NVM_PATH_WAS ]]; then return fi NVM_PATH_WAS=$NVM_PATH if [[ -f "$NVM_PATH/.nvmrc" ]]; then nvm use $(<"$NVM_PATH/.nvmrc") else nvm use default fi } if [[ "$PROMPT_COMMAND" ]]; then export PROMPT_COMMAND="$PROMPT_COMMAND;automatic-nvm-use" else export PROMPT_COMMAND=automatic-nvm-use fi

Then re-open your terminals, or reinitialize them via source ~/.bashrc.

Note: If your ~/.bashrc contains other code that changes $PROMPT_COMMAND (like making your terminal's title reflect the current directory), make sure it does not simply set a new $PROMPT_COMMAND, but prepends or appends itself. Alternatively, put the above snippet after it.

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Arne Hartherz
Last edit:
about 8 hours ago
by Arne Hartherz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more