Git Branch in One minute
What is a git branch?
Branch is a feature supported in the Git, that allow you to diverge from a main line of development and continue to do your work without messing with that main line.
On this article, i present the main git commands to handle the branches.
Listing branches
List local branches
git branch
List remote branches
Remote branch are all the branches in the server repository (you may are hosting your repo in github, gitlab or bitbucket)
git branch -r
List all branches
git branch -a
Creating branches
Create and switch to a branch
git checkout -b my-branch
The command above is a shorthand for those two commands below.
Create a branch
git branch my-branch
Switch to a branch
git checkout my-branch
Switch between branches
git checkout branch-name
Upload your branch to remote server
After creating your branch, for the first time, you should send the branch to the server with those commands.
git push -u origin branch-name
Or
git push --set-upstream origin branch-name
But in next time, just do a normal push.
git push
Download a remote branch
git checkout --track origin/branch-name
Merge a branch to current branch
git merge branch-name
Imagine you want to copy/merge all changes/commits from a branch to another branch, you can use the commands below.
In this example, we are to copy all changes/commits from dev to main.
Switch to a branch
First we must switch to the branch that we want to put/paste the commits.
git checkout main
Merge
Then we need to merge/copy all changes/commits from the branch we want to.
git merge dev
Delete branch
Delete local branch
git branch -d branch-name
Force delete local branch
git branch -D branch-name
Delete remote branch
git push origin --delete branch-name
Refresh list of remote branches
After a remote branch is deleted, if still visible when you execute git branch -r, you should update the list using the command below.
git remote update origin --prune
Rename branch
Rename current branch
git branch -m new-branch-name
Rename a branch
git branch -m old-branch-name new-branch-name