Reputation: 5171
I have seen many somewhat similar stackoverflow questions regarding this. I have tried many ways but am still stuck.
I have a script like this:
git fetch --prune
for k in $(git branch --merged| grep -E -v "(^\*|master|dev|release|origin)"); do
if [ -z "$(git log -1 --since='38 week ago' -s "$k")" ]; then
## Info about the branches before deleting
git log -1 --format="%ci %ce - %H $k" -s "$k";
## Delete from the remote
# git push origin --delete "$k";
## Delete the local branch, regardless of whether it's been merged or not
# git branch -D "$k"
fi;
done
I see:
host:folder user$ clean-up.sh
2018-05-18 14:46:25 -0700 [email protected] - 646766c885324b4f298d55604e0aabc2a00fdb58 feature/some-branch
2018-05-16 19:56:56 -0400 [email protected] - 4e09733554eaf5e293ca7c668c19ec1395b361f9 some-other-branch
So it says these two following branches are to be deleted:
feature/some-branch
some-other-branch
But they have actually been deleted from remote some time ago. The problem is my local repo still have them. I have tried many ways sync my local repo with the remote so that branches that are deleted from remote will also be deleted from local.
Would anyone know of a good solution?
An even better solution is to not depending on local repo at all and be able to clean up old branches in remote by purely depend on the remote repo.
I have tried git remote prune origin but it didn't work
Upvotes: 4
Views: 1843
Reputation: 19476
One liner
git branch -d $(git branch -vv | grep ': gone]' | cut -d' ' -f3)
This will delete local branches that are gone, but it will leave those that are not yet merged. Use -D instead if you don't need those either.
Tested on git version 2.32.1 (Apple Git-133)
Upvotes: 0
Reputation: 5171
Learned something new. I needed git branch -r to look at the remote branches. And when I do that, I need to get rid of the "origin" from the branch names. And then when I want to find out the info about the branch, I need to add "origin" back in. Here is what works for me:
for k in $(git branch -r --merged | sed 's/origin\///' | grep -E -v "(^\*|master|dev|release|origin)"); do
if [ -z "$(git log -1 --since='5 week ago' -s "origin/$k")" ]; then
## Info about the branches before deleting
git log -1 --format="%ci %ce - %H $k" -s "origin/$k";
## Delete from the remote
git push origin --delete "$k";
## Delete the local branch, regardless of whether it's been merged or not
# git branch -D "$k"
fi;
done
Upvotes: 0