How do I delete a local and remote branch in git

You can use “git branch -D” or “git branch –delete” to delete a local branch. Further, you can use git push to delete the remote copy in the online repository. Let us see with a practical hands-on. In this example, we would delete both local and remote copies of a branch maincopy.

The initial setup is as shown. There are two branches – main and maincopy. “git branch” would also show the respective remote copies of the branches.

~/repoone$ git branch -a
* main
  maincopy
  remotes/origin/HEAD -> origin/main
  remotes/origin/main
  remotes/origin/maincopy

Use “git branch -D” to delete the local branch. “git branch -a” would show that the local branch got removed. But, the remote copy is still there.

~/repoone$ git branch -D maincopy
Deleted branch maincopy (was 59968f9).

~/repoone$ git branch
* main

~/repoone$ git branch -a
* main
  remotes/origin/HEAD -> origin/main
  remotes/origin/main
  remotes/origin/maincopy

Use git push to delete the remote branch as shown.

~/repoone$ git push origin --delete maincopy
To github.com:codeversionmaster/repoone.git
 - [deleted]         maincopy

You can now see the final state. Both local and remote branches got removed.

~/repoone$ git branch -a
* main
  remotes/origin/HEAD -> origin/main
  remotes/origin/main