Git branch Command: A Comprehensive Guide
In Git, branching is a powerful feature that allows you to create new branches of your codebase and work on different features and fixes without affecting the main codebase. With Git’s branch command, you can create, rename, delete, and view branches. In this guide, we’ll dive into the Git branch command and learn how to use it in detail.
Creating a New Branch
Git branch command allows you to create a new branch with the following syntax:
git branch <branch-name>
For example, let’s create a new branch called "feature-1" using the command:
git branch feature-1
This will create a new branch, but you are still on the original branch. To switch to the new branch, use the Git checkout command:
git checkout feature-1
This will switch you to the new branch, and you can start making changes and committing them.
Renaming a Branch
Git branch command also allows you to rename a branch using the following syntax:
git branch -m <old-branch-name> <new-branch-name>
For example, let’s rename our "feature-1" branch to "new-feature" using the command:
git branch -m feature-1 new-feature
This will rename the branch from "feature-1" to "new-feature".
Deleting a Branch
If you no longer need a branch, you can delete it using the Git branch command with the -d option:
git branch -d <branch-name>
For example, let’s delete our "new-feature" branch using the command:
git branch -d new-feature
Viewing Branches
To view all branches in your Git repository, use the Git branch command with no arguments:
git branch
This will list all the branches with an asterisk indicating the current branch.
You can also view remote branches using the following command:
git branch -r
This will list all the remote branches in your Git repository.
Tracking a Remote Branch
Git branch command allows you to track a remote branch using the following syntax:
git branch --track <new-branch-name> <remote-branch-name>
For example, let’s track a remote branch called "new-remote-branch" and create a new local branch called "new-local-branch" using the command:
git branch --track new-local-branch new-remote-branch
This will create a new local branch called "new-local-branch" that tracks the remote branch called "new-remote-branch".
Conclusion
Git branch command is a powerful tool that allows you to create, rename, delete, and view branches in your Git repository. With this guide, you should now have a better understanding of how to use the Git branch command in your day-to-day workflow. Happy branching!