2

Is there a command to sync the remote and local branches?

For example, I have deleted few branches from remote which are no longer useful using command git remote update --prune. Now I have these deleted branches locally.

Is there a command to delete the local branch if there exists no remote copy of same branch?

nwinkler
  • 52,665
  • 21
  • 154
  • 168

2 Answers2

2

git fetch --prune should do what you are looking for.

David Deutsch
  • 17,443
  • 4
  • 47
  • 54
  • That didn't helped mate. I still have local branches which were deleted from remote. – Sandeep Dongapure Jun 24 '15 at 12:52
  • Sorry I'm late to the party. I just had to do the same thing as OP and through I'd share. I deleted branch `my-feature` from the remote after merging the associated PR. This left 2 `my-feature`-related refs in my local repo: local branch `my-feature` as well as `origin/my-feature`. `git fetch --prune` is used to remove `origin/my-feature` while `git branch -d my-feature` is used to delete the local branch. Hope this helps any fellow archaeologists! – wbadart May 17 '19 at 22:24
0

There is no built-in command in Git for this task. You have to write a script in your favorite language. I'll use Powershell but you can always transform it to some fancy *SH one-liner.

Test rig

Script: gist.github.com/tkirill/7c14331de4da814069af. It does:

  1. Creates a repo test-repo with two branches: branch1 and branch2.
  2. Clones the repo to test-clone, and goes to this clone and checkouts all branches. The last step effectively creates corresponding local branches.
  3. Removes branches branch1 and branch2 on origin.
  4. Leaves you in test-clone.

Removing branches

Script: gist.github.com/tkirill/0f0f1902beb0c0723582. It does:

  1. Gets local branches.
  2. Gets remote branches without remote name.
  3. Removes every local branch that not exists on remote.

Running experiment

.\test-rig.ps1
..\remove-local-branches.ps1

Output of the last command shows us that both branch1 and branch2 were deleted:

Removing branch branch1
Deleted branch branch1 (was ab1575a).
Removing branch branch2
Deleted branch branch2 (was c9a24c2).

But that's not the end

Writing such script can be pretty tricky if you want a universal solution. For example, the script takes branches from all remotes, not only origin. You may want to work with origin only.

But the main problem from my point of view is that it can remove local branches which not merged in develop.

Remove merged branches only

I think this is really what you need. Merged branches have little use. There are a lot of scripts and aliases doing this task since, it is really common. Choose what you like the most :) As for Windows I wrote corresponding extension for posh-git.

Kirill
  • 3,364
  • 2
  • 21
  • 36