@devius 的出色回答。
我只是对其进行了扩展,以便在将带有.nvmrc 的目录留给另一个没有它的目录时,它可以恢复为默认版本。
~/.bashrc:
#
# Run 'nvm use' automatically every time there's
# a .nvmrc file in the directory. Also, revert to default
# version when entering a directory without .nvmrc
#
enter_directory() {
if [[ $PWD == $PREV_PWD ]]; then
return
fi
PREV_PWD=$PWD
if [[ -f ".nvmrc" ]]; then
nvm use
NVM_DIRTY=true
elif [[ $NVM_DIRTY = true ]]; then
nvm use default
NVM_DIRTY=false
fi
}
export PROMPT_COMMAND=enter_directory
按照@doug-barbieri的建议,如果当前目录下没有.nvmrc文件但父子目录中有一个,下面的脚本不会将node改回默认版本目录。
~/.bashrc:
enter_directory() {
if [[ $PWD == $PREV_PWD ]]; then
return
fi
if [[ "$PWD" =~ "$PREV_PWD" && ! -f ".nvmrc" ]]; then
return
fi
PREV_PWD=$PWD
if [[ -f ".nvmrc" ]]; then
nvm use
NVM_DIRTY=true
elif [[ $NVM_DIRTY = true ]]; then
nvm use default
NVM_DIRTY=false
fi
}
诀窍就在这里:
if [[ "$PWD" =~ "$PREV_PWD" && ! -f ".nvmrc" ]]; then
return
fi
它检查 PWD 是否包含 PREV_PWD。例如,如果/home/user1/a/b 包含/home/user1/a。
这可以扩展为与 Starship 一起使用(即使在 Windows 而非 WSL 的 Git Bash 上)也可以使用 starship_precmd_user_func
set_win_title() {
BASEPWD=$(basename "$PWD")
echo -ne "\033]0; ? $BASEPWD \a" < /dev/null
if [[ $PWD == $PREV_PWD ]]; then
return
fi
if [[ "$PWD" =~ "$PREV_PWD" && ! -f ".nvmrc" ]]; then
return
fi
PREV_PWD=$PWD
if [[ -f ".nvmrc" ]]; then
nvm use
NVM_DIRTY=true
elif [[ $NVM_DIRTY = true ]]; then
nvm use default
NVM_DIRTY=false
fi
}
starship_precmd_user_func="set_win_title"
eval "$(starship init bash)"