Git branch commands
Git branches provide a powerful way to manage project flow, organize code changes, and collaborate on different features or bug fixes simultaneously.
In this section, we will explore a wide range of Git branch commands that allow you to create, switch, merge, and delete branches, providing you with the flexibility to work on multiple code paths within your project. We will cover essential commands for creating a branch, switching between branches, and merging changes.
By mastering Git branch commands, you will gain the ability to structure your codebase effectively, work on features in isolation, and experiment without impacting the main branch. Whether you are working on a personal project or part of a larger development team, understanding branch commands is crucial for maintaining a clean and organized codebase.
Explore Git branch commands and unlock the power of code branching in your software development projects.
Show list of branches
$ git branch
The current branch will be highlighted in green and marked with an asterisk.
Adding the -r
option will also list the remote tracking branches. Adding the -a
option will show both remote and local branches.
Create branch
$ git branch <branchname>
See:
Rename branch
$ git branch -m <oldbranch> <newbranch>
Delete branch
$ git branch -d <branchname>
If the branch has not been fully merged with an upstream branch, or in HEAD if there is no upstream, Git will not allow you to delete the branch. However, you can specify -D
to force delete it irrespective of its merge status.
See:
Switch branches
$ git checkout <branch>
This will allow you to check out and switch to your desired branch.
Adding the -b
option will create a new branch and switch to it.
See:
Merge branches
$ git merge <branch>
Adding the --no-ff
option will cause a git merge command to always create a merge commit instead of fast-forwarding. This is useful because it allows you to retain the historical information of a branch before it was merged.
When you add the --squash
option, Git creates a single commit that represents the merged changes instead of creating a merge commit. This commit contains the changes from the merged branch but doesn't contain any of the information associated with the merged branch or the merge process itself.
See: