In Git, a branch is simply a lightweight movable pointer to commits and a part of development process. At the time of development the developers are creating a new branch that later can be merged in to the production codebase. In this article we will show you how to create and list local and remote Git branches.
List Git Branches
Use the git branch
or git branch --list
command to list all local Git branches:
dev
stagging
hotfix
* master
The asterisk (*
) indicates that is the current branch. In above example master
is the current branch.
To list the both local and remote branches pass -a
option with the command:
git branch -a
dev
stagging
hotfix
* master
remotes/origin/dev-a
You can use -r
option to list only the remote branches:
git branch -r
Creating a Git Branch
It’s very easy to create a branch, to create a local branch use the git branch command followed by the name of the new branch. For example, to create a new branch with name test-branch
, you would type:
git branch test-branch
It will not return anything output. If the branch with same already exists it will show a error message like below:
fatal: A branch named 'test-branch' already exists.
Ensure that before working on branch, you should select the branch using git checkout
command followed by the branch name:
git checkout test-branch
In output it will print message that the branch is switched:
Switched to branch 'test-branch'
If you would like to create a branch and switched to it using one command, you can do it using the -b
option with git checkout command:
git checkout -b test-branch
Switched to branch 'test-branch'
Now, your branch is selected and you can now use the git add
and git commit
commands to add commits to the new branch.
Push the new branch on the remote repository, use the git push
command followed by the remote repository name and branch name:
git push remote-repo-name test-branch
Conclusion
We have show how to create local and remote Git branches. With the git branch command, you can also Rename and Delete local and remote Git branches.
If you have any questions or suggestion, please leave a comment below.