Git delete all merged in local branches I have written a shell script utility for deleting all merged local branches.

#!/usr/bin/env bash

# Remove references to remote branches that no longer exist.
git remote prune origin
# Create a file containing list of all merged branches.
git branch --merged &gt; 5db3bb3c-718a-444c-b1ce-d90a5a0d1cb3.clc

nano 5db3bb3c-718a-444c-b1ce-d90a5a0d1cb3.clc
# Trim trailing and leading whitespace etc.
sed 's/^[ \t]*//;s/[ \t]*$//' &lt; 5db3bb3c-718a-444c-b1ce-d90a5a0d1cb3.clc
# Soft delete all branches left in the file and then remove tmp file.
xargs git branch -d &lt; 5db3bb3c-718a-444c-b1ce-d90a5a0d1cb3.clc
rm 5db3bb3c-718a-444c-b1ce-d90a5a0d1cb3.clc


Although I wrote this only for personal use, I will likely create a repository for it on my github account and I am not particularly familiar with shell script best practices.

(Edit: The script eventually ended up on github here)
Improve your file handling:


Don't use a hard coded file name for temporary files.
Don't spew temporary files into the current directory.
Make sure you clean up temporary files even on error.


The first two can be addressed by leveraging mktemp. The last can be addressed with a trap.

branchesfile=$(mktemp)
trap "{ rm -f $branchesfile; }" EXIT


You should also honor the user's choice of default editor, rather than require nano. You can get the user's editor preference with git var GIT_EDITOR:

$(git var GIT_EDITOR) $branchesfile


Git tools typically honor the exit code of the editor. If the editor exited with error, this should stop the script:

if [ $? -ne 0 ]; then
    exit 1
fi


This allows the user to cancel the operation if they spot a problem they don't want to fix at the moment.

Putting this all together:

#!/usr/bin/env bash
branchesfile=$(mktemp)
trap "{ rm -f $branchesfile; }" EXIT

# Remove references to remote branches that no longer exist.
git remote prune origin
# Create a file containing list of all merged branches.
git branch --merged &gt; $branchesfile

$(git var GIT_EDITOR) $branchesfile
if [ $? -ne 0 ]; then
    exit 1
fi

# Trim trailing and leading whitespace etc.
sed 's/^[ \t]*//;s/[ \t]*$//' &lt; $branchesfile
# Soft delete all branches left in the file and then remove tmp file.
xargs git branch -d &lt; $branchesfile


There's one other issue: your script will try to keep going if any other commands error out. set -e is one option to solve this, but there are caveats to using it. If you choose to use set -e, you'll need to revise the exit code checking of the editor, since bash will exit before it gets to the if.