Git Branching and Merging
Creating and Deleting Branches
Creating Branches in Git
Branches allow working on different features, bug fixes, or experiments in isolation within a project. Creating a new branch is a simple and powerful process in Git.
Create a New Branch
To create a new branch, use the git branch
command:
bash
Example:
bash
This command creates a new branch called feature-xyz
based on the current branch.
Switching and Creating Branches Simultaneously
Often, after creating a branch, you will want to switch to it. You can do this in a single step using the git checkout -b
command:
bash
Example:
bash
This command creates and switches to the new branch feature-xyz
.
View All Branches
To see all branches in your repository, use:
bash
The command lists all local branches, highlighting the current branch with an asterisk (*
).
Renaming a Branch
You can rename an existing branch using:
bash
Example:
bash
This command renames feature-xyz
to feature-new
.
Deleting Branches in Git
Once a branch is no longer needed, for example, after merging it with the main branch, it can be deleted to keep the repository clean.
Delete a Local Branch
To delete a local branch, use:
bash
Example:
bash
This command deletes the branch feature-xyz
.
Forcibly Deleting a Branch
If the branch you are trying to delete has not been merged, Git will show a warning message. To force the deletion, use:
bash
Example:
bash
This command forces the deletion of feature-xyz
, even if it has not been merged.
Delete a Remote Branch
Remote branches can also be deleted. To delete a remote branch, use the git push
command with the --delete
option:
bash
Example:
bash
This command deletes the remote branch feature-xyz
from the remote repository origin
.
Summary
- Create a branch:
git branch <branch-name>
- Create and switch to a new branch:
git checkout -b <branch-name>
- View all branches:
git branch
- Rename a branch:
git branch -m <old-name> <new-name>
- Delete a local branch:
git branch -d <branch-name>
- Delete a remote branch:
git push origin --delete <branch-name>
Proper branch management facilitates an organized and efficient workflow. In the next chapter, we will learn how to navigate between branches in Git.
- 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