Skip to content

Instantly share code, notes, and snippets.

@paddy74
Created September 4, 2024 14:47
Show Gist options
  • Save paddy74/0264fe38120261edafe559ee1e0ff030 to your computer and use it in GitHub Desktop.
Save paddy74/0264fe38120261edafe559ee1e0ff030 to your computer and use it in GitHub Desktop.
Remove all local branches that are not on remote
# from https://stackoverflow.com/a/33548037/7706917
#
# Explanation:
# ---
# Switch to the main branch
# $> git checkout main
# Prune remote branches
# $> git remote update origin --prune # Prune remote branches
# Get a verbose output of all branches (git reference)
# $> git branch -vv
# Get only the records where they have been removed from remote.
# > | Select-String -Pattern ": gone]"
# Gets the branch name
# > | % { $_.toString().Trim().Split(" ")[0]}
# Deletes the branch
# > | % {git branch -d $_}
# Soft drop
function Soft-Drop {
git checkout main; git fetch --prune; git branch -vv | Select-String -Pattern ": gone]" | % { $_.toString().Trim().Split(" ")[0]} | % {git branch -d $_}
}
# Hard drop
function Hard-Drop {
git checkout main; git fetch --prune; git branch -vv | Select-String -Pattern ": gone]" | % { $_.toString().Trim().Split(" ")[0]} | % {git branch -D $_}
}
# Run the command, account for command line parameters
if ( $($args.count) -eq 0 )
{
Soft-Drop
}
elseif ( $args[0] -eq "-D" -or $args[0] -eq "--force" )
{
Hard-Drop
}
else
{
Write-Output "Invalid command line parameter $args[0] or invalid number of command line parameters"
exit 1
}
#!/bin/sh
# from https://stackoverflow.com/a/33548037/7706917
#
# Explanation:
# ---
# Switch to the main branch
# $> git checkout main
# Prune remote branches
# $> git remote update origin --prune # Prune remote branches
# Get a verbose output of all branches (git reference)
# $> git branch -vv
# Get only the records where they have been removed from remote.
# > | awk '/: gone]/{print $1}'
# Deletes the branch
# > | xargs git branch -d
# Soft drop
soft_drop () {
git checkout main && git fetch --prune && git branch -vv | awk '/: gone]/{print $1}' | xargs git branch -d
}
# Hard drop
hard_drop () {
git checkout main && git fetch --prune && git branch -vv | awk '/: gone]/{print $1}' | xargs git branch -D
}
# Run the command, account for command line parameters
if [ $# -eq 0 ]; then
soft_drop
elif [ $1 -eq "-D" ] || [ $1 -eq "--force" ]; then
hard_drop
else
echo "Invalid command line parameter $1"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment