Git is a powerful version control system that allows developers to manage their codebase efficiently. One of the key functionalities in Git is managing branches, which is essential for organizing development workflows and isolating features or fixes. This guide focuses on the ‘git branch’ command, which is used for creating, deleting, and listing branches within a repository.
Creating a New Branch:
To create a new branch in Git, use the following command:
git branch new-feature
This command creates a new branch named ‘new-feature’ based on the current branch. To verify that the branch was created, you can list all branches:
git branch
Listing Branches:
To list all branches in the repository, use:
git branch -a
This command lists both local and remote branches. The output will show all branches along with the current branch indicated with an asterisk (*).
Switching Branches:
To switch to a different branch, use:
git checkout new-feature
This command switches your working directory to the ‘new-feature’ branch. You can then make changes specific to that branch.
Deleting a Branch:
To delete a branch, use:
git branch -d new-feature
This command deletes the ‘new-feature’ branch. If the branch has unmerged changes, use -D
instead of -d
to force deletion.
Rename a Branch:
To rename a branch, you can use:
git branch -m new-name
This renames the current branch to ‘new-name’.
Creating a Remote Branch:
To create a new branch on a remote repository, use:
git push origin new-feature
This command creates a new branch named ‘new-feature’ on the remote repository ‘origin’. To verify, list remote branches:
git branch -r
Merging Branches:
To merge a branch into the current branch, use:
git merge new-feature
This command merges the changes from ‘new-feature’ into the current branch. Resolve any conflicts that may arise during the merge.
Viewing Branch History:
To view the commit history of a branch, use:
git log new-feature
This command displays the commit history specific to the ‘new-feature’ branch.
Checking Out a Specific Commit:
To check out a specific commit on a branch, use:
git checkout
This allows you to temporarily switch to a specific commit on the current branch.
Tracking a Remote Branch:
To start tracking a remote branch locally, use:
git checkout -b new-local-branch origin/new-remote-branch
This command creates a new local branch ‘new-local-branch’ that tracks ‘new-remote-branch’ from the remote repository ‘origin’.
Discussion about this post