<commit_before>---
layout: post
title: "Cleaning up old git branches"
date: 2015-03-13 13:00
comments: true
categories: [Programming, Productivity]
---

With some git commands and bash scripting we can clean up old branches quickly.

The final solution looks like this:

``` bash
g old | head -n5 | xargs bash -c 'git branch -D $@; git push origin --delete $@;' bash
```

##### Breaking it down

1. Using a git alias we can list branches by the date they were committed to, with the oldest at the top.
1. The output is limited with `head` and `-n`, for example 5 items is `head -n5`.
1. `xargs` provides each branch as `$@` which is substituted in each of the next commands.
1. We execute the normal command to delete the branch locally and from a remote named `origin`.

##### Listing old git branches

Add the following alias to your `~/.gitconfig`.

```
[alias]
  old = for-each-ref --sort=committerdate --format='%(refname:short)' refs/heads/
```

##### Deleting a single branch

When I know I don't want a branch locally or on the remote server anymore, I use this function to delete it in both places:

```
function gdel { git branch -D $1; git push origin --delete $1; }
```
<commit_msg>Edits<commit_after>---
layout: post
title: "Cleaning up old git branches"
date: 2015-03-13 13:00
comments: true
categories: [Programming, Productivity]
---

With git commands and bash scripting we can clean up old branches quickly.

The final solution looks like this:

``` bash
g old | head -n5 | xargs bash -c 'git branch -D $@; git push origin --delete $@;' bash
```

##### Breaking it down

1. We can list branches by the date they were committed to, with the oldest at the top. This is added as a git alias.
1. Branch names output is limited with `head` and `-n`, for example for 5 items: `head -n5`
1. `xargs` provides each branch name as `$@` substituted in to each of the following git commands.
1. git commands to delete the branch locally and from a remote named `origin` are executed for each branch name.

##### Listing old git branches

Add the following alias to your `~/.gitconfig`.

```
[alias]
  old = for-each-ref --sort=committerdate --format='%(refname:short)' refs/heads/
```

##### Deleting a single branch

When I no longer want a branch locally or on the remote server, I use this function to delete both at once:

```
function gdel { git branch -D $1; git push origin --delete $1; }
```

{'fraction_non_alphanumeric': 0.11221945137157108, 'fraction_numerical': 0.017456359102244388, 'mean_word_length': 3.7288801571709236, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1454066', 'n_tokens_mistral': 757, 'n_tokens_neox': 699, 'n_words': 370}