1️⃣ Save the following script in:
📂 .config/fish/functions/git-delete-branches.fish
2️⃣ Execute the command:
git-delete-branches "<regex>"
🔹 Finds and deletes local/remote branches matching a regex.
🔹 Asks for confirmation to avoid surprises.
🔹 Saves time and keeps your repo clean.
📌 Full code and explanation 👉
#!/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 |
Top comments (0)