From e06f73577640dfd1a146464bdb55d0288fdf70d8 Mon Sep 17 00:00:00 2001 From: Daniel Li Date: Thu, 26 Jul 2018 16:13:07 +0100 Subject: [PATCH] Improve Bash alias This will take into account nested directories inside your main project directory --- README.md | 67 +++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 48 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 373a951..0a6b55a 100644 --- a/README.md +++ b/README.md @@ -386,30 +386,59 @@ If you prefer a lighter-weight solution, the recipes below have been contributed Put the following at the end of your `$HOME/.bashrc`: ```bash +find-up () { + path=$(pwd) + while [[ "$path" != "" && ! -e "$path/$1" ]]; do + path=${path%/*} + done + echo "$path" +} + cdnvm(){ - cd $@ - if [[ -f .nvmrc && -s .nvmrc && -r .nvmrc ]]; then - <.nvmrc nvm install; - elif [[ $(nvm current) != $(nvm version default) ]]; then - nvm use default; - fi + cd $@; + nvm_path=$(find-up .nvmrc | tr -d '[:space:]') + + # If there are no .nvmrc file, use the default nvm version + if [[ ! $nvm_path = *[^[:space:]]* ]]; then + + declare default_version; + default_version=$(nvm version default); + + # If there is no default version, set it to `node` + # This will use the latest version on your machine + if [[ $default_version == "N/A" ]]; then + nvm alias default node; + default_version=$(nvm version default); + fi + + # If the current version is not the default version, set it to use the default version + if [[ $(nvm current) != "$default_version" ]]; then + nvm use default; + fi + + elif [[ -s $nvm_path/.nvmrc && -r $nvm_path/.nvmrc ]]; then + declare nvm_version + nvm_version=$(<"$nvm_path"/.nvmrc) + + # Add the `v` suffix if it does not exists in the .nvmrc file + if [[ $nvm_version != v* ]]; then + nvm_version="v""$nvm_version" + fi + + # If it is not already installed, install it + if [[ $(nvm ls "$nvm_version" | tr -d '[:space:]') == "N/A" ]]; then + nvm install "$nvm_version"; + fi + + if [[ $(nvm current) != "$nvm_version" ]]; then + nvm use "$nvm_version"; + fi + fi } alias cd='cdnvm' ``` -This alias would automatically detect a `.nvmrc` file in the directory you're `cd`ing into, and switch to that version. And when you `cd` back, it will automatically switch back to the `default` version. - -If you prefer one-liners: - -``` -alias cd='cdnvm(){ cd $@; if [[ -f .nvmrc && -s .nvmrc && -r .nvmrc ]]; then <.nvmrc nvm install; elif [[ $(nvm current) != $(nvm version default) ]]; then nvm use default; fi; };cdnvm' -``` - -You may also run this directly on your terminal: - -```bash -$ echo 'alias cd='\''cdnvm(){ cd $@; if [[ -f .nvmrc && -s .nvmrc && -r .nvmrc ]]; then <.nvmrc nvm install; elif [[ $(nvm current) != $(nvm version default) ]]; then nvm use default; fi; };cdnvm'\''' >> ~/.bashrc -``` +This alias would search 'up' from your current directory in order to detect a `.nvmrc` file. If it finds it, it will switch to that version; if not, it will use the default version. #### zsh