Search code examples
bashnvm

Command 'nvm' not found in .bashrc


I'm trying to create a function in my .bashrc file to change a symbolic link every time I use "nvm use".

change_sl() {
   local version="$1"
   ln -sf "$NVM_DIR/versions/node/$version/bin/node" /usr/bin/node
}
nvm() {
   if ["$1" = "use" ]; then
     local version="$2"
     command nvm "$1" "$version"
     change_sl "$(node -v)"
else
     command nvm "$@"
   fi
}

but I have this error : Command 'nvm' not found, but there are 13 similar ones.

I'm quite new to bash so if anyone can help me with this that would be great.


Solution

  • NVM itself is a shell function rather than an external executable. As such, you can't invoke nvm with command. To quote the documentation of the command builtin:

    Run command with args suppressing the normal shell function lookup. Only builtin commands or commands found in the PATH are executed.

    As Bash also does not support inheritance or super calls, you first have to create a copy of the original nvm function with a different name so that you can call it directly, e.g.

    eval "$(echo "nvm_orig()"; declare -f nvm | tail -n +2)"
    
    function nvm() {
      nvm_orig "$@"
      if [ "$1" = "use" ]; then
        change_sl "$(node -v)"
      fi
    }
    

    The technique to create a copy of a function under a different name was shown by Evan Broder.