Chuck's Academy

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

  1. Create a branch: git branch <branch-name>
  2. Create and switch to a new branch: git checkout -b <branch-name>
  3. View all branches: git branch
  4. Rename a branch: git branch -m <old-name> <new-name>
  5. Delete a local branch: git branch -d <branch-name>
  6. 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.


Ask me anything