The source code for this blog is available on GitHub.

Ali Ismail's Blog.

Branch Hopping with Git

Cover Image for Branch Hopping with Git
Ali Ismail
Ali Ismail

Git Branch Hopping

Switching branches is vital to efficiently work on Git. However, if you're not careful you can easily jump into the wrong branch, or worse, invite unwanted changes by accident.

Branch Hopping Tactics

In most cases you'll want to branch off your main branch to another one. Let's say you want to switch to 'main' but you are not sure if you're there already. You can always confirm what branch you're on by using the following command. git branch

Let's say it turns out you're not on main, the next thing you want to do is make sure you avoid any uncommitted changes that you might have forgotten about. Checking the status is a great way to ensure you're good to go and not accidentally add more to your commit than you intended. git status

In the case that you do have added, removed, or modified files that are not relevant to what you want to do, you can always stash them away and unpack them. git stash

Now that you're jumping from a clean spot and not bringing in unintended changes, you can switch branches by specifying the branch name to go to. Let's go to 'main' because that's the most stable branch and we want to make changes relative to where 'main' i scurrently. git checkout main

In order to make a copy of what you have in your current 'main' branch, you can branch a copy of what you have with a new name. Let's call it NewBranchName. git checkout -b bug/new-branch-name

And there you have it, you've now successfully branch hopped:

  • You've made a copy of where main is
  • You're have a (hopefully) helpful name on what you're going to achieve in this branch
  • You've avoided bringing in any unintended changes from a previous work you were engaged in.

Things go terribly wrong

If you didn't go to main first, you'll be making a copy of another branch. This can go terribly wrong if that branch has changes that are no longer useful or break things that are working. When you eventually merge, you'll likely be merging in breaking changes that will not be fun to debug. This can be manageable if you have well documented your work into verbose commits and pull requests, and you might need to step back and forth in time to extrapolate the useful work and get rid of the unwanted changes.

Things can also go terribly wrong if you do not stash unwanted work. That would be literally bringing incomplete baggage from another branch into your new branch.