-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdelete-stale-branches.sh
More file actions
49 lines (43 loc) · 1.71 KB
/
delete-stale-branches.sh
File metadata and controls
49 lines (43 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/bin/bash
# Asks user confirmation to proceed
while true; do
read -p "This command will delete all local branches that no longer exist in the remote repository. Do you wish to continue? ([Y]es/[N]o/[A]ll) " confirm
if [[ "$confirm" == "Y" || "$confirm" == "y" || "$confirm" == "N" || "$confirm" == "n" || "$confirm" == "A" || "$confirm" == "a" ]]; then
break
else
echo "Invalid input. Please enter a valid option."
fi
done
if [[ "$confirm" == "N" || "$confirm" == "n" ]]; then
echo "Operation canceled."
exit 1
fi
# Gets the list of local branches
local_branches=$(git branch --format '%(refname:short)')
# Gets the list of remote branches
remote_branches=$(git ls-remote --heads origin | awk '{print $2}' | sed 's#refs/heads/##')
# Iterates over each local branch and deletes it if it doesn't exist in the remote repository
for branch in $local_branches; do
if [[ "$branch" != "master" && "$branch" != "main" && ! "$remote_branches" =~ "$branch" ]]; then
if [[ "$confirm" == "A" || "$confirm" == "a" ]]; then
git branch -D "$branch"
echo "Local branch \"$branch\" deleted."
else
while true; do
read -p "Do you want to delete local branch \"$branch\"? (Y/N) " confirm_delete
if [[ "$confirm_delete" == "Y" || "$confirm_delete" == "y" || "$confirm_delete" == "N" || "$confirm_delete" == "n" ]]; then
break
else
echo "Invalid input. Please enter a valid option."
fi
done
if [[ "$confirm_delete" == "Y" || "$confirm_delete" == "y" ]]; then
git branch -D "$branch"
echo "Local branch \"$branch\" deleted."
else
echo "Local branch \"$branch\" kept."
fi
fi
fi
done
echo "Operation complete."