Delete local Git branches after deleting them on the remote repo

前端 未结 12 1984
死守一世寂寞
死守一世寂寞 2020-11-30 16:26

I want to have my local and remote repositories always in sync in terms of branches.

After a Pull Request review on GitHub, I merge and remove my branch there (remot

12条回答
  •  借酒劲吻你
    2020-11-30 16:58

    I use the same flow with GitHub, and didn't find the previous answers satisfying me, as git branch --merged lists branches which were merged, but not every of them was removed remotely in my case. So, this worked for me:

    git fetch --all -p; git branch -vv | grep ": gone]" | awk '{ print $1 }' | xargs -n 1 git branch -d

    where:

    • git fetch --all -p: update local branches status
    • git branch -vv: list local branches status
    • grep ": gone]": filter deleted ones
    • awk '{ print $1 }': extract their names
    • xargs -n 1 git branch -d: pass the name to the delete command

    Note: if you prefer, you could use -D instead of -d, which enforces the delete.

    For example:

    someUsr@someHost:~/repo$ git branch -a
    basic-testing
    integration-for-tests
    * master
    origin
    playground-for-tests
    test-services
    remotes/origin/HEAD -> origin/master
    remotes/origin/basic-testing
    remotes/origin/master
    remotes/origin/test-services
    
    someUsr@someHost:~/repo$ git fetch --all -p; git branch -vv | grep ": gone]" | awk '{ print $1 }' | xargs -n 1 git branch -d
    Fetching origin
    Deleted branch integration-for-tests (was fbc609a).
    Deleted branch playground-for-tests (was 584b900).
    
    someUsr@someHost:~/repo$ git branch -a
    basic-testing
    * master
    origin
    test-services
    remotes/origin/HEAD -> origin/master
    remotes/origin/basic-testing
    remotes/origin/master
    remotes/origin/test-services
    

    Reference:

    http://git-scm.com/book/en/v2/Git-Branching-Remote-Branches

提交回复
热议问题