run `nvm use` automatically every time there's a .nvmrc file on the directory

前端 未结 10 1840
南笙
南笙 2020-12-23 11:05

How to configure my shell so that nvm use run automatically every time there\'s a .nvmrc file on the directory and use the latest version or a global config whe

10条回答
  •  没有蜡笔的小新
    2020-12-23 11:23

    Extending on @Adriano P answer, I'd propose this version that is less general (only works if .nvmrc is set on a git repository root), but works in cases when we navigate to elsewhere in project than its root:

    _enter_dir() {
        local git_root
        git_root=$(git rev-parse --show-toplevel 2>/dev/null)
    
        if [[ "$git_root" == "$PREV_PWD" ]]; then
            return
        elif [[ -n "$git_root" && -f "$git_root/.nvmrc" ]]; then
            nvm use
            NVM_DIRTY=1
        elif [[ "$NVM_DIRTY" == 1 ]]; then
            nvm use default
            NVM_DIRTY=0
        fi
        PREV_PWD="$git_root"
    }
    
    export PROMPT_COMMAND=_enter_dir
    #export PROMPT_COMMAND="$PROMPT_COMMAND;_enter_dir"  # use this if PROMPT_COMMAND already defined
    

提交回复
热议问题