Created
June 4, 2025 02:45
-
-
Save ridhoperdana/45d47aabe9d3190a1ae7d1f0c5dcf582 to your computer and use it in GitHub Desktop.
Delete Git Branch except...
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
#!/bin/bash | |
if [ -z "$1" ]; then | |
echo "Usage: $0 [branch-1,branch-2,...]" | |
exit 1 | |
fi | |
# Convert input string into array | |
IFS=',' read -ra KEEP_BRANCHES <<< "$1" | |
# Convert array to grep pattern | |
KEEP_PATTERN=$(printf "|^%s$" "${KEEP_BRANCHES[@]}") | |
KEEP_PATTERN="${KEEP_PATTERN:1}" # remove leading | | |
# Get list of local branches | |
ALL_BRANCHES=$(git branch --format="%(refname:short)") | |
# Filter branches to delete | |
BRANCHES_TO_DELETE=$(echo "$ALL_BRANCHES" | grep -vE "$KEEP_PATTERN") | |
# Confirmation prompt | |
echo "Branches to delete:" | |
echo "$BRANCHES_TO_DELETE" | |
echo | |
read -p "Are you sure you want to delete these branches? (y/N): " confirm | |
if [[ ! "$confirm" =~ ^[Yy]$ ]]; then | |
echo "Aborted." | |
exit 0 | |
fi | |
# Delete branches | |
echo "$BRANCHES_TO_DELETE" | xargs -n 1 git branch -D |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment