https://github.com/fibo/cleanup_git_branches
remove unused git branches with one command
https://github.com/fibo/cleanup_git_branches
branches git
Last synced: 4 months ago
JSON representation
remove unused git branches with one command
- Host: GitHub
- URL: https://github.com/fibo/cleanup_git_branches
- Owner: fibo
- License: mit
- Created: 2022-08-05T11:19:43.000Z (almost 4 years ago)
- Default Branch: main
- Last Pushed: 2024-05-28T16:17:38.000Z (about 2 years ago)
- Last Synced: 2025-04-15T06:39:03.919Z (about 1 year ago)
- Topics: branches, git
- Language: Shell
- Homepage:
- Size: 6.84 KB
- Stars: 3
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# cleanup_git_branches
> Remove unused git branches
[](https://fibo.github.io/kiss-literate-programming)
## Usage
Simply launch the following command in a git repo
```sh
cleanup_git_branches
```
## Installation
Both *zsh* and *bash* shell are supported.
Just copy and paste the `cleanup_git_branches` function below in your shell profile or (assuming you are using zsh) do something like
```sh
mkdir -p ~/.shell
cd ~/.shell
git clone https://github.com/fibo/cleanup_git_branches.git
echo "source ~/.shell/cleanup_git_branches/fun.sh" >> ~/.zshrc
```
With the setup above, to update run the following
```sh
cd ~/.shell/cleanup_git_branches
git pull origin main
source ~/.zshrc
cd -
```
## Annotated source
To generate sources, enter this repo folder and run `make`.
Create a `cleanup_git_branches` function
cleanup_git_branches() {
Get current working branch and repo default branch.
WORKING_BRANCH=`git rev-parse --abbrev-ref HEAD`
DEFAULT_BRANCH=`basename $(git symbolic-ref refs/remotes/origin/HEAD)`
Go to default branch.
if [ "$DEFAULT_BRANCH" != "$WORKING_BRANCH" ]; then
git switch $DEFAULT_BRANCH
fi
Remove local branches (excluding main branch) that are already merged.
git branch --merged | grep -v $DEFAULT_BRANCH | while read branch
do
git branch -d $branch
done
Remove local branches with no remote reference.
git fetch -p
for BRANCH_NAME in $(git branch -v | grep '\[gone\]' | awk '{print $1}')
do
git branch -D $BRANCH_NAME
done
Back to previous branch.
if [ "$DEFAULT_BRANCH" != "$WORKING_BRANCH" ]; then
git switch $WORKING_BRANCH
fi
}
## Tip
If you need to change default branch, once done remotely (for instance on GitHub), you need
to update your local repository.
Assuming the new default branch is `main`, launch
```sh
git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/main
```
## License
[MIT](https://fibo.github.io/mit-license)