DustinToothless DustinToothless - 3 months ago 9
Node.js Question

Bash script for changing NVM Node version

I'm trying to add an alias to my

.bash_profile
to do the following:



  • xx projname
    =>
    cd ~/folder_1/projname
    and use node version
    6 on nvm if nvm is currently using some other version

  • yy projname
    =>
    cd ~/folder_2/projname
    and use node version 4 on nvm if nvm is currently using some other version




I have currently implemented everything except the last portion i.e.
if nvm is currently using some other version
like so:

function xx { cd ~/folder_1/"$1"; nvm use v6;}
function yy { cd ~/folder_2/"$1"; nvm use v4;}


What is the best way to handle the outstanding task? What I want is something like this:


run
nvm current
and see if index of
v6
is false, and then run
nvm use v6



But I'm really new to bash and can't seem to find a way to do this. TIA!

Answer

You want to get the version. From comments you say it comes like this:

$ nvm current
v6 <blabla>

So you need to catch the first word of nvm current's output:

read version _ <<< $(nvm current)

Then it is a matter of comparing the value with "v6". I would use:

if [ "$version" == "v6" ]; then
   ...
fi

All together:

function yy {
    cd ~/folder_2/"$1"
    read version _ <<< $(nvm current)
    if [ "$version" == "v6" ]; then
        nvm use v4
    fi
}
Comments