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
- Switch branch:
git checkout <branch-name>
- List branches:
git branch
- Show current branch:
git branch --show-current
- Quick switch to previous branch:
git checkout -
- Switch to a remote branch:
git fetch origin
andgit checkout -b <branch-name> origin/<branch-name>
- Switch branch with uncommitted work:
git stash
andgit 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.
- Introduction to Git
- Initial Setup and Basic Workflow
- Basic Concepts of Branches in Git
- Creating and Deleting Branches
- Branch Navigation
- Branch Merging
- Resolución de Conflictos de Fusión
- Merge Strategies: Fast-Forward vs. Recursive
- Rebase in Git: Concepts and Uses
- Merge vs. Rebase: When to Use Each
- Remote Branches and Their Management
- Git Flow and Other Workflow Models
- Best Practices for Branching and Merging
- Advanced Tools and Commands
- Conclusion and Final Recommendations