OZZIE
OZZIE

Reputation: 7348

Bash check if nvm installed

How can I detirmine if nvm (Node Version Manager) is installed in bash?

I already have it installed in my system but I haven't been able to make any bash script that can detect it. I am making a script that should be used by others which depends on nvm, so I want to output if it's not installed and exit if it isn't..

This doesn't work: https://stackoverflow.com/a/26759734/846348 it says that nvm isn't installed but the bash script can use nvm..

Would be nice if it supported Mac Terminal, Mac iTerm and Windows with Linux shell at least.

Upvotes: 3

Views: 11776

Answers (2)

Martin Zeitler
Martin Zeitler

Reputation: 76719

One can check with command -v nvm:

$ command -v nvm >/dev/null 2>&1 || { echo >&2 "nvm is required, but it's not installed.  Aborting."; exit 1; }

Upvotes: 4

Christopher Peisert
Christopher Peisert

Reputation: 24144

The nvm install script checks if nvm is installed using roughly the following logic:

if [ -d "${HOME}/.nvm/.git" ]; then echo "nvm installed"; else echo "nvm not installed"; fi

This just checks if the directory ~/.nvm/.git exists.

To exit with failure if the directory ~/.nvm/.git does not exist, you could use:

if [ ! -d "${HOME}/.nvm/.git" ]; then exit; fi

Check if nvm installed using a Makefile

NVM_EXISTS := $(shell if [ -d "${HOME}/.nvm/.git" ]; then echo "nvm installed"; fi)

.PHONY: check
check:
ifndef NVM_EXISTS
    $(error Please install nvm: https://github.com/nvm-sh/nvm)
endif

Note on nvm install.sh

The actual install script uses the following functions to determine the nvm installation directory (rather than assuming ${HOME}/.nvm). But if you are using the default location ${HOME}/.nvm, you can skip these checks.

nvm_default_install_dir() {
  [ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm"
}

nvm_install_dir() {
  if [ -n "$NVM_DIR" ]; then
    printf %s "${NVM_DIR}"
  else
    nvm_default_install_dir
  fi
}

Upvotes: 5

Related Questions