Last active
February 19, 2025 06:02
-
-
Save pookdeveloper/bdc574f785940316a13b5ed4e63fda06 to your computer and use it in GitHub Desktop.
Git delete branches by regex in local and remote
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env fish | |
function git-delete-branches | |
# Ensure a regex argument is provided | |
if test (count $argv) -lt 1 | |
echo "Usage: git-delete-branches '<regex>'" | |
return 1 | |
end | |
set -l regex $argv[1] | |
# Find local and remote branches matching the regex | |
set -l branches ( | |
begin | |
git branch --list --format "%(refname:short)" | |
git branch --remotes --format "%(refname:short)" | sed 's|origin/||' | |
end | sort -u | grep -E "$regex" | |
) | |
if test -z "$branches" | |
echo "No branches matching the pattern: $regex" | |
return 0 | |
end | |
echo "The following branches were found:" | |
printf "%s\n" $branches | |
# Add a blank line for readability | |
echo "" | |
read -l -P "Are you sure you want to delete these branches? [y/N] " confirm | |
if test "$confirm" != y | |
echo "Operation canceled." | |
return 0 | |
end | |
# Delete local branches | |
for branch in $branches | |
if git show-ref --verify --quiet "refs/heads/$branch" | |
git branch -D "$branch" | |
end | |
end | |
# Delete remote branches | |
for branch in $branches | |
if git ls-remote --exit-code origin "$branch" >/dev/null 2>&1 | |
git push origin --delete "$branch" | |
end | |
end | |
echo "Process completed." | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment