Search code examples
gitgit-ls-remote

How to delete remote refs from git matching a filter?


While moving from GitLab to GitHub, after I executed git push --mirror <URL>, I noticed that git ls-remote --refs (in the target repository on GitHub) displayed some refs starting with the refs/merge-requests/ prefix.

Since they are irrelevant to GitHub (they are only used by GitLab),
I want to delete them; how can I do it?

In other words, how can I delete refs from a remote matching a search/filter criterion?


Solution

  • You could use this one-liner shell script to do so (you can use this on Windows, too, e.g. using Git Bash):

    git ls-remote --refs             \
        | grep refs/merge-requests/  \
        | cut -f 2                   \
        | xargs -I {} git push --delete origin {}
    

    Summary:

    • List remote refs
    • Include only the `merge-requests refs from the list
    • Extract only ref names
    • Execute git push --delete origin on each matching ref to delete them from remote.

    Notes:

    • A drawback of this solution is that this deletes refs one by one, so it can take some time to delete hundreds of remote refs
    • Modify the script accordingly if your remote's name is not origin (though it probably is)