Skip to content

Instantly share code, notes, and snippets.

@axelson
Last active August 14, 2022 20:14
Show Gist options
  • Save axelson/161262067e18c4278bb4621980f5ae9b to your computer and use it in GitHub Desktop.
Save axelson/161262067e18c4278bb4621980f5ae9b to your computer and use it in GitHub Desktop.
Run `git save-branch` to save the current branch so you don't lose work

Run git config --global alias.save-branch '!~/scripts/git-save-branch.sh (customize the path to match where you save the script to)

Now you can run git save-branch to run the script

#!/bin/bash
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
if git diff --exit-code; then
echo "Clean dir";
else
echo "Error: git diff reports non-clean directory";
exit 1;
fi
find_new_branch_name()
{
branch_name=$1
suffix=$2
new_branch_name="$1-$2"
if [ "$suffix" -ge 5 ]; then
exit 1;
fi
if git rev-parse --quiet --verify "$new_branch_name"; then
next_suffix=$((suffix + 1))
find_new_branch_name "$branch_name" "$next_suffix"
else
git branch "$new_branch_name"
echo "Created new branch $new_branch_name"
fi
}
find_new_branch_name "save-$CURRENT_BRANCH" 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment