Skip to content

Instantly share code, notes, and snippets.

@jrnewell
Last active August 29, 2015 14:03
Show Gist options
  • Save jrnewell/10d75ba000b8cf1bfa8f to your computer and use it in GitHub Desktop.
Save jrnewell/10d75ba000b8cf1bfa8f to your computer and use it in GitHub Desktop.
BASH script to upgrade a local (user-level) node.js installation automatically
#!/usr/bin/env bash
# check arguments
if [ $# -ne 1 ]; then
echo "Usage: `basename $0` version" >&2
exit 1
fi
VERSION=$1
echo "Upgrading to node.js $VERSION"
echo "Downloading node-v${VERSION}-darwin-x64.tar.gz"
cd "/Users/james/Downloads"
NODE_URL="http://nodejs.org/dist/v${VERSION}/node-v${VERSION}-darwin-x64.tar.gz"
curl $NODE_URL | tar xf -
if [ $? -ne 0 ]; then
echo "Error downloading: $NODE_URL"
exit 1
fi
echo "Moving package to local directory"
mv "./node-v${VERSION}-darwin-x64" "/Users/james/local/node-${VERSION}"
if [ $? -ne 0 ]; then
echo "Error moving ./node-v${VERSION}-darwin-x64 to /Users/james/.node-${VERSION}"
exit 1
fi
cd "/Users/james/local/node-${VERSION}"
if [ $? -ne 0 ]; then
echo "Error changing working directory to /Users/james/local/node-${VERSION}"
exit 1
fi
echo "Updating better coffescript path"
BETTER_COFFEESCRIPT="/Users/james/Library/Application Support/Sublime Text 3/Packages/User/CoffeeScript.sublime-settings"
sed -E -i'.bak' "s/node\-[0-9]+\.[0-9]+\.[0-9]+/node-$VERSION/g" "$BETTER_COFFEESCRIPT"
rm -f "$BETTER_COFFEESCRIPT.bak"
echo "Updating bash profile path"
BASH_PROFILE="/Users/james/.bash_profile"
sed -E -i'.bak' "s/node\-[0-9]+\.[0-9]+\.[0-9]+/node-$VERSION/g" "$BASH_PROFILE"
BASH_PROFILE_OLD="/Users/james/bash_profile.bak"
mv -f "$BASH_PROFILE.bak" "$BASH_PROFILE_OLD"
PROFILE_DIFFSTAT=`diff "$BASH_PROFILE" "$BASH_PROFILE_OLD" | diffstat -t | tail -n +2`
if [ "$PROFILE_DIFFSTAT" != "1,1,0,unknown" ]; then
BASH_PROFILE_NEW="/Users/james/bash_profile.new"
echo "Unexpected diffstat between $BASH_PROFILE and $BASH_PROFILE_NEW"
echo "$PROFILE_DIFFSTAT"
mv "$BASH_PROFILE" "$BASH_PROFILE_NEW"
mv "$BASH_PROFILE_OLD" "$BASH_PROFILE"
exit 1
fi
rm -f "$BASH_PROFILE_OLD"
echo "Installing global libraries"
PACKAGES=`npm -g list --depth=0 --parse`
# change path to new node root
export PATH=${PATH//$NODE_HOME\/bin?/}
rm -rf $NODE_HOME
export NODE_HOME="/Users/james/local/node-${VERSION}"
PATH=$NODE_HOME/bin:$PATH
echo "updating npm to latest version"
npm -g update npm
echo "cleaning cache"
npm cache clean
for DEP_PATH in $PACKAGES; do
DEPENDENCY=`basename $DEP_PATH`
if [ "$DEPENDENCY" != "lib" -a "$DEPENDENCY" != "npm" ]; then
echo "Installing $DEPENDENCY"
npm -g install $DEPENDENCY
fi
done
echo "Done upgrading to node.js $VERSION"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment