Skip to content

Instantly share code, notes, and snippets.

@bpatram
Last active February 18, 2019 15:27
Show Gist options
  • Save bpatram/a61dd641d1e9c7117982c9ab01c410ef to your computer and use it in GitHub Desktop.
Save bpatram/a61dd641d1e9c7117982c9ab01c410ef to your computer and use it in GitHub Desktop.
Stash your current changes, pull down latest master, then go back to your branch and apply the stash
#! /bin/bash -e
# ---------------------------
# Author: Brandon Patram
# Date: 2018-06-19
#
# Description: Pull a branch down without losing your current state
# Will stash your current changes and re-apply them after pulling
# down the target branch (or master if not defined)
#
# Usage: inplace-pull.sh [path to repo] [branch to pull=master]
# Examples:
# inplace-pull.sh path/to-repo master
# inplace-pull.sh path/to-repo develop
# inplace-pull.sh path/to-repo
# ---------------------------
STASH_MESSAGE=$(uuidgen)
GIT_DIR=$1
TARGET_BRANCH=$2
if [[ -z "$GIT_DIR" ]]; then
echo "No path to git repo specified"
exit 1
else
cd $GIT_DIR
fi
if [[ -z "$TARGET_BRANCH" ]]; then
TARGET_BRANCH=master
echo "No target branch specified. Will use $TARGET_BRANCH instead"
fi
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
echo "Stashing current changes: $STASH_MESSAGE..."
git stash push -q -u -m "$STASH_MESSAGE"
# find stash number from message
# since we use a uuid lets assume we will only ever get one match
STASH_ID=$(git stash list -n 1 --grep=$STASH_MESSAGE | cut -f 1 -d ':')
git checkout -q $TARGET_BRANCH
echo "Pulling $TARGET_BRANCH..."
git pull -q origin $TARGET_BRANCH
echo "Restoring original state of $CURRENT_BRANCH..."
git checkout -q $CURRENT_BRANCH
# if a stash was made/found, pop it
# its possible a stash was not created if there was nothing to stash
if ! [[ -z "$STASH_ID" ]]; then
git stash pop -q "$STASH_ID"
fi
echo "Done!"
@bpatram
Copy link
Author

bpatram commented Feb 18, 2019

Future progress moved to: https://github.com/slewsystems/scripts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment