Git: Branch Management
Branch management in Git involves creating, listing, switching, renaming, and deleting branches. Branches allow you to work on different features or fixes independently without affecting the main codebase.
Create a new branch
To create a new branch, use the following command:
Basic command to create a new branch
git branch <branch-name> Replace <branch-name> with the desired name for your new branch.
Create and switch to a new branch
git checkout -b <branch-name>This command creates a new branch and switches to it immediately.
List branches
To list branches in your repository, use:
List local branches
git branchList ALL branches (local+remote)
git branch -aSwitch between branches
To switch to a different branch, use:
git checkout <branch-name> Replace <branch-name> with the name of the branch you want to switch to.
git switch <branch-name>This is an alternative command to switch branches, introduced in Git 2.23.
Upstream branch
Upstream is a remote branch that your local branch tracks e.g. synchronizes with when you run git pull or git push.
Check current upstream
git branch -vvThis command shows the current branch and its upstream branch.
Set upstream branch
When a branch is created locally, it does not have an upstream branch set by default. You can set the upstream branch when you push the branch for the first time using:
git push -u origin <branch-name> If the branch <branch-name> does not exist on the remote, it will be created and set as the upstream for your local branch.
Without the -u flag, the branch will be pushed but not set as upstream.
Alternatively, you can set or change the upstream branch for an existing local branch using:
git branch --set-upstream-to=origin/feature/branch-name feature/branch-name Where feature/branch-name is the name of your local branch and origin/feature/branch-name is the corresponding remote branch.
Delete a branch
Delete a local branch
git branch -d <branch-name>This command deletes the specified local branch. It will only delete the branch if it has been fully merged.
git branch -D <branch-name>This command forcefully deletes the specified local branch, even if it hasn't been merged.
Delete a remote branch
git push origin --delete <branch-name>This command deletes the specified branch from the remote repository.
Rename a branch
Rename a local branch
git branch -m <new-branch-name> This command renames the current branch to <new-branch-name>.
Rename a different local branch
git branch -m <old-branch-name> <new-branch-name> This command renames <old-branch-name> to <new-branch-name>.
Rename a remote branch
Renaming a remote branch involves deleting the old branch and pushing the renamed local branch to the remote:
git push origin --delete <old-branch-name>This command deletes the old branch on the remote.
git push -u origin <new-branch-name>This command pushes the local branch to the remote and sets it as the upstream branch.