Created
February 20, 2022 16:35
-
-
Save ksamuel/a9ad167856052bcc7bdfa725ddacb183 to your computer and use it in GitHub Desktop.
A script to automatically stash uncommited work when one switches branch in git
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -o errtrace # err traps works in functions | |
set -E -o errexit # exit on error | |
#set -o pipefail # don't hide errors in pipes => can't use this one, it fails on grep -q | |
set -o nounset # exit on undeclared variable | |
set -o xtrace # trace everything | |
IFS=$'\n' # Field separator is a new line | |
CURDIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" | |
shopt -s dotglob # * include hidden files | |
if [ $# -ne 1 ]; then | |
echo "You need to pass the branch name" | |
exit 1 | |
fi | |
CURRENT_BRANCH="$(git branch --show-current)" | |
TARGET_BRANCH="$1" | |
CURRENT_BRANCH_STASH_NAME="switcheroo: $CURRENT_BRANCH" | |
TARGET_BRANCH_STASH_NAME="switcheroo: $TARGET_BRANCH" | |
# Make sure the branch we switch to exists | |
if ! git show-ref --quiet "refs/heads/$TARGET_BRANCH"; then | |
echo "Branch '$TARGET_BRANCH' cannot be found" | |
exit 1 | |
fi | |
# Stash the entire working copy, tag it with the current branch name | |
# then switch to the other branch | |
git stash save --include-untracked -m "$CURRENT_BRANCH_STASH_NAME" | |
git switch "$TARGET_BRANCH" | |
# If the other branch has some saved stash, restore it and delete it | |
if git stash list | grep -q "$TARGET_BRANCH_STASH_NAME"; then | |
stash_ref=$(git stash list | grep "$TARGET_BRANCH_STASH_NAME" | head -n 1 | cut -f1 -d":") | |
git stash apply "$stash_ref" | |
git stash drop "$stash_ref" | |
fi | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment