Chuck's Academy

Git Branching and Merging

Branch Navigation

Branch Navigation in Git

Branch navigation is an essential skill in Git, allowing you to move between different work contexts within a repository quickly and efficiently. This is particularly useful when working on multiple features or bug fixes in parallel.

Branch Switching

To switch from one branch to another, use the git checkout command:

bash

Example:

bash

This command switches to the feature-xyz branch.

Listing Branches

It’s always good to know which branch you’re on and see the other available branches. Use the following command to list all branches:

bash

The asterisk (*) indicates the branch you are currently on.

Example:

In this example, you are on the main branch.

Viewing the Current Branch

If you're only interested in knowing which branch you are on, you can use:

bash

This command shows the name of the current branch.

Switching to the Previous Branch

Sometimes, it's useful to quickly move back to the previous branch you were working on. This can be done with:

bash

Example:

Suppose you are on main and switched to feature-xyz:

bash

To quickly return to main:

bash

Switching to a Remote Branch

If you want to switch to a remote branch that you haven't checked out locally yet, you first need to fetch the remote branch information and then switch to it:

bash

Example:

bash

These commands fetch the feature-abc branch information from the remote repository and create a local branch with the same name based on the remote branch.

Branch Navigation with Uncommitted Work

If you try to switch branches and have uncommitted changes in your working directory, Git won't allow the switch unless you stash the changes. You can stash the changes and then switch branches:

bash

And then retrieve your changes:

bash

Summary

  1. Switch branch: git checkout <branch-name>
  2. List branches: git branch
  3. Show current branch: git branch --show-current
  4. Quick switch to previous branch: git checkout -
  5. Switch to a remote branch: git fetch origin and git checkout -b <branch-name> origin/<branch-name>
  6. Switch branch with uncommitted work: git stash and git stash pop

Navigating between branches allows you to work in multiple contexts without losing focus. In the next chapter, we will explore how to merge branches in Git to integrate changes from one branch to another.


Ask me anything