Local branching in Git allows developers to isolate work into separate contexts, making it easier to manage features, fixes, and experiments without affecting the main codebase. This guide covers essential operations like creating, deleting, renaming branches, and syncing them with remote repositories.
Understanding local branches in Git
A local branch in Git is a version of your repository that diverges from the main line of development. This allows you to work freely without impacting the main codebase or other branches. When you create a branch, Git records new commits on that branch only. This makes branches ideal for developing new features or testing ideas.
Creating a local branch
To start a new feature or fix, you'll first need to create a local branch:
git branch <branch_name>
Alternatively, you can create and switch to the new branch in one command:
git checkout -b <branch_name>
Deleting a local branch
When you're done with a branch, or if it's no longer needed, you can delete it to tidy up your repository:
git branch -d <branch_name> # Safe delete; fails if there are unmerged changesgit branch -D <branch_name> # Force delete; removes the branch regardless of its merge status
Renaming a local branch
If you need to rename a branch, perhaps to reflect a change in the scope or purpose of the work, you can do so easily:
If you are on the branch:
Terminalgit branch -m <new_branch_name>If you are on a different branch:
Terminalgit branch -m <old_branch_name> <new_branch_name>
Pushing a local branch to remote
To share a local branch with teammates or to back up your work on a remote server, you'll need to push it:
git push -u origin <branch_name>
The -u
flag sets the upstream tracking, linking your local branch to a remote branch.
Resetting a local branch to match remote
If your local branch has diverged from the remote branch, or if you need to reset it for any reason, you can sync it back to the state of the remote branch:
git fetch origingit reset --hard origin/<branch_name>
This will align your local branch with the remote, discarding any local changes.
Removing local branches that are no longer on remote
Sometimes, branches get deleted from the remote repository, and you might want to clean up your local repository to reflect this:
git fetch --prune
This command fetches the latest branch list from the remote and removes any local tracking branches that no longer exist on the remote.
Renaming a branch on both local and remote
If you rename a branch that has already been pushed to the remote, you'll need to delete the old branch remotely and push the new one:
git push origin --delete <old_branch_name>git push -u origin <new_branch_name>
For more information see the official Git documentation.