Skip to content

Instantly share code, notes, and snippets.

@usmanity
Created June 14, 2023 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save usmanity/c55ae2754aa5ffd074e87166ee11c273 to your computer and use it in GitHub Desktop.
Save usmanity/c55ae2754aa5ffd074e87166ee11c273 to your computer and use it in GitHub Desktop.
Goes from feature branch to main/master branch, pulls and switches back to feature branch and then rebases
#!/bin/zsh
# Step 1: Get the current branch name
current_branch=$(git symbolic-ref --short HEAD)
# Step 2: Determine the target branch
target_branch="main" # Default to "main" branch
if ! git show-ref --verify --quiet "refs/heads/$target_branch"; then
target_branch="master" # Use "master" branch if "main" doesn't exist
fi
# Step 3: Pull the latest changes on the target branch
echo "Switching to $target_branch branch..."
git checkout $target_branch
git pull origin $target_branch
# Step 4: Go back to the original branch
echo "Switching back to $current_branch branch..."
git checkout $current_branch
# Step 5: Rebase the original branch with the target branch
echo "Rebasing $current_branch onto $target_branch..."
git rebase $target_branch
# Step 6: Check if the rebase encountered conflicts
if [[ $? -ne 0 ]]; then
# Step 6: Rebase failed, cancel and inform the user
echo "Rebase failed. Cancelling the rebase..."
git rebase --abort
echo "Rebase cancelled."
exit 1
fi
# Step 7: Rebase successful
echo "Rebase completed successfully."
exit 0
@bezhermoso
Copy link

I like the auto-detection of target branch!

If you care about it, you can actually skip the back-and-forth between branches done in L14-19 by:

git fetch origin/$target_branch

Then, the rebase command can be changed to:

git rebase origin/$target_branch

@usmanity
Copy link
Author

@bezhermoso thanks for the suggestion, I will update and try it out and then update this gist ◡̈

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