How to delete a branch both locally and remotely in git?

After completing my work on a branch in Git, I want to delete it both locally and remotely. How can I achieve this?

Add Comment
1 Answer(s)
Firstly, ensure that you have finished all of your work on the branch and safely merged it into the main branch if needed, as you will not be able to recover it once it is deleted. **To delete the branch locally:** Use the command: ``` git branch -d branch_name ``` The `-d` option will delete the branch only if it has already been fully merged in its upstream branch. If you want to force delete it regardless of its merged status, use `-D` instead. **To delete the branch remotely:** Use this command: ``` git push origin --delete branch_name ``` This tells `git` to push a deletion of `branch_name` to the `origin` remote. This is the same as: ``` git push origin :branch_name ``` The `:` before the branch name indicates to `git` that you want to push nothing into `branch_name` on `origin`, effectively deleting it. Remember to replace `branch_name` with the actual name of your branch. Just be certain when deleting branches, especially remotely, since it's a destructive operation that can't be undone. Always double-check your branch name and make sure your work is secured somewhere else (like in another branch or in the main branch) before deleting.
Answered on July 17, 2023.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.