Louth
Louth

Reputation: 12393

Delete all local Git branches

I follow a development process where I create a new local branch for every new feature or story card. When finished I merge the branch into master and then push.

What tends to happen over time due to a combination of laziness or forgetfulness, is that I end up with a large list of local branches, some of which (such as spikes) may not have been merged.

I know how to list all my local branches and I know how to remove a single branch but I was wondering if there was a Git command that allows me to delete all my local branches?

Below is the output of the git branch --merged command.

cd ~/projects/application
git branch --merged

Output:

  STORY-123-Short-Description
  STORY-456-Another-Description
  STORY-789-Blah-Blah
* master

All attempts to delete branches listed with grep -v \* (as per the answers below) result in errors:

error: branch 'STORY-123-Short-Description' not found.
error: branch 'STORY-456-Another-Description' not found.
error: branch 'STORY-789-Blah-Blah' not found.

I'm using:

Upvotes: 748

Views: 684614

Answers (30)

Rudy Huynh
Rudy Huynh

Reputation: 608

If you work with NodeJS, I wrote this command:

npx git-clear-branch

The command clears all of your local branch except master, main and current branch.

Upvotes: 17

M.Qassem
M.Qassem

Reputation: 371

First (switch to the branch you want to keep > for example: 'master'):

git checkout master

Second (make sure you are on 'master')

git branch -D $(git branch)

If you're using PowerShell, use:

git branch -D $(git branch).Trim()

Upvotes: 36

Ali Hamad
Ali Hamad

Reputation: 839

To remove all your local Git branches, but keep main:

git branch | grep -v "main" | xargs git branch -D

Upvotes: 24

forvaidya
forvaidya

Reputation: 3315

Use:

git branch -l | grep -v master | xargs git branch -D

But what care deleting the branch; just remove the workspace and reclone it if it is a small repository!!

Upvotes: 11

Kellen Stuart
Kellen Stuart

Reputation: 8933

Here's the PowerShell solution for anyone running on a Windows machine:

git checkout master # By being on the 'master' branch,
                    # you won't be able to delete it
foreach($branch in (git branch))
{
    git branch -D $branch.Trim()
}

Upvotes: 17

ScottyBlades
ScottyBlades

Reputation: 14063

I recommend a more moderate answer. Many of the answers here use -D which is forced delete regardless of whether changes have been merged or not. Here is a one-liner which leaves untouched the branches which have unmerged changes.

git branch --merged | egrep -v "(^\*|master|dev)" | xargs git branch -d

Or you can try other examples listed, but just change the -D to -d. I know the OP asked how to delete, but in most use cases, it’s safer to use -d.

Upvotes: 3

kapil
kapil

Reputation: 1749

If you want to keep master, develop and all remote branches, delete all local branches which are not present on GitHub any more.

git fetch --prune

git branch | grep -v "origin" | grep -v "develop" | grep -v "master" | xargs git branch -D
  1. It will delete remote refs that aren't in use any longer on the remote repository.

  2. This will get list of all your branches. Remove branch containing master, develop or origin (remote branches) from the list. Delete all branches in list.

Warning: This deletes your own local branches as well. So do this when you have merged your branch and doing a cleanup after merge: delete.

Upvotes: 9

Ron Newcomb
Ron Newcomb

Reputation: 3302

I don't have grep or other Unix commands on my box, but this worked from Visual Studio Code's terminal:

git branch -d $(git branch).trim()

I use the lowercase d, so it won't delete unmerged branches.

I was also on master when I did it, so * master doesn't exist, so it didn't attempt deleting master.

Upvotes: 3

geoom
geoom

Reputation: 8207

The simpler way to delete all branches but keeping others like "develop" and "master" is the following:

git branch | grep -v "develop" | grep -v "master" | grep -v "main" | xargs git branch -D

On Windows machines (PowerShell):

git branch | %{ $_.Trim() } | ?{ $_ -ne 'master' } | ?{ $_ -ne 'main'} | ?{ $_ -ne 'develop'} | %{ git branch -D $_ }

It is very useful!

Upvotes: 661

mBardos
mBardos

Reputation: 3097

I found a nicer way in a comment on this issue on GitHub:

git branch --merged master --no-color | grep -v "master\|stable\|main" | xargs git branch -d

This includes the no-color option and excluding of the stable branch (add other branches as needed in your case).

Upvotes: 200

culebrón
culebrón

Reputation: 36513

I found it easier to just use a text editor and the shell.

  1. Type git checkout <TAB> in the shell. It will show all local branches.
  2. Copy them to a text editor, and remove those you need to keep.
  3. Replace line breaks with spaces. (In Sublime Text, it's super easy.)
  4. Open the shell, and type git branch -D <PASTE THE BRANCHES NAMES HERE>.

That's it.

Upvotes: 30

4u.Ans
4u.Ans

Reputation: 1279

I had a similar kind of situation and recently found the following command useful.

git branch -D `git branch | awk '{ if ($0 !~ /<Branch_You_Want_to_Keep>/) printf "%s", $0 }'`

If you want to keep multiple branches, then

git branch -D `git branch | awk '{ if ($0 !~ /<Branch_You_Want_to_Keep1>|<Branch_You_Want_to_Keep2>/) printf "%s", $0 }'`

Upvotes: 16

Adam Dymitruk
Adam Dymitruk

Reputation: 129734

Just a note; I would upgrade to Git 1.7.10. You may be getting answers here that won't work on your version. My guess is that you would have to prefix the branch name with refs/heads/.

Caution: Proceed with the following only if you made a copy of your working folder and .git directory.

I sometimes just go ahead and delete the branches I don't want straight from .git/refs/heads. All these branches are text files that contain the 40 character SHA-1 hash value of the commit they point to. You will have extraneous information in your .git/config file if you had specific tracking set up for any of them. You can delete those entries manually as well.

Upvotes: 43

tmaj
tmaj

Reputation: 35115

git for-each-ref \
    --format="%(if) %(HEAD) %(then) %(else) %(refname:short) %(end)" \
    refs/heads/ |
xargs -r git branch -D

This:

  1. Doesn't use a porcelain git branch
  2. Uses the official (from git-for-each-ref help page) way of identifying the current branch

Parts:

  1. git for-each-ref --format="..." refs/heads/ finds all branches that are not the current branch
    • %(HEAD) finds if the branch is the current branch so "%(if) %(HEAD) %(then) %(else) %(refname:short) %(end) prints an empty line for the current branch. From help:
      • We ignore space when evaluating the string before %(then), this is useful when we use the %(HEAD) atom which prints either "*" or " " and we want to apply the if condition only on the HEAD ref.

    • %(refname:short) -from help:
      • For a non-ambiguous short name of the ref append :short.

  2. xargs -r git branch -D deletes the branch
    • -r, or --no-run-if-empty, makes the xarg ignore the empty line for the current branch

Upvotes: 6

Will
Will

Reputation: 153

For anyone who wants a windows Command Prompt solution:

Delete all branches other than master:

FOR /f "tokens=*" %i IN ('git branch ^| findstr /v "master"') DO git branch -d %i

Delete all branches with any string matches in the branch name:

FOR /f "tokens=*" %i IN ('git branch ^| findstr "TargetName"') DO git branch -d %i

Three things to note:

  1. git branch -d will only delete branches that have been merged. If you want to delete branches regardless of whether they've been merged or not, you can use git branch -D instead.
  2. It will not delete the branch you are currently checking out.
  3. If you want to put this command into a batch file, you need to double the % signs. This is a quirk of batch file scripting where % signs are treated as special characters and need to be escaped by doubling them.

Upvotes: 1

Sohail Shrestha
Sohail Shrestha

Reputation: 768

Delete All Local Branches in Local


Use this as this is pretty simple. This will delete all the branches on your computer and not on remote repository.

 git branch -D $(git branch) 

Upvotes: 19

chris
chris

Reputation: 53

If you are using windows, try this in powershell

git branch | Select-String -notmatch "master" | ForEach-Object {$_.ToString().Trim()} | ForEach-Object {git branch -D $_}

Upvotes: 3

siliconrockstar
siliconrockstar

Reputation: 3664

git branch | grep release-1.4 | xargs -n 1 -I % sh -c 'git branch -D %'

Easy way to delete all the branches with a name that matches the pattern 'release-1.4*'. I also use it periodically with ticket prefixes to delete all my local working branches, but leave pipeline branches unbothered.

Upvotes: 2

GoZoner
GoZoner

Reputation: 70215

The 'git branch -d' subcommand can delete more than one branch. So, simplifying @sblom's answer but adding a critical xargs:

git branch -D `git branch --merged | grep -v \* | xargs`

or, further simplified to:

git branch --merged | grep -v \* | xargs git branch -D 

Importantly, as noted by @AndrewC, using git branch for scripting is discouraged. To avoid it use something like:

git for-each-ref --format '%(refname:short)' refs/heads | grep -v "master\|main" | xargs git branch -D

Caution warranted on deletes!

$ mkdir br
$ cd br; git init
Initialized empty Git repository in /Users/ebg/test/br/.git/
$ touch README; git add README; git commit -m 'First commit'
[master (root-commit) 1d738b5] First commit
 0 files changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 README
$ git branch Story-123-a
$ git branch Story-123-b
$ git branch Story-123-c
$ git branch --merged
  Story-123-a
  Story-123-b
  Story-123-c
* master
$ git branch --merged | grep -v \* | xargs
Story-123-a Story-123-b Story-123-c
$ git branch --merged | grep -v \* | xargs git branch -D
Deleted branch Story-123-a (was 1d738b5).
Deleted branch Story-123-b (was 1d738b5).
Deleted branch Story-123-c (was 1d738b5).

Upvotes: 847

Pravin Bansal
Pravin Bansal

Reputation: 4691

Try the following shell command:

git branch | grep -v "master" | xargs git branch -D

Explanation:

  • Get all branches (except for the master) via git branch | grep -v "master" command
  • Select every branch with xargs command
  • Delete branch with xargs git branch -D

Upvotes: 149

Premraj
Premraj

Reputation: 74641

Deleting many local branches at once

# delete all local unmerged branches
git branch --no-merged | egrep -v "(^\*|master|dev)" | xargs git branch -D
# delete all local branches (merged and unmerged).
git branch | egrep -v "(^\*|master|dev)" | xargs git branch -D  

Deleting remote branches

# Deleting non-existent tracking branches
git remote prune <remote> --dry-run
# Deleting a single remote branch
git push <remote> --delete <branch>
# Deleting many remote branches at once
git branch -r --merged | egrep -v "(^\*|master|dev)" | sed 's/origin\///' | xargs -n 1 git push origin --delete

Source

Upvotes: 4

kgsnaidu
kgsnaidu

Reputation: 374

If you want to delete all your local branches, here is the simple command:

git branch -D `git branch`

Note: This will delete all the branches except the current checked out branch

Upvotes: 20

Dimitar Grivov
Dimitar Grivov

Reputation: 41

git branch -d [branch name] for local delete

git branch -D [branch name] also for local delete but forces it

Upvotes: 4

Andriy Orehov
Andriy Orehov

Reputation: 61

For this purpose, you can use git-extras

$ git delete-merged-branches
Deleted feature/themes (was c029ab3).
Deleted feature/live_preview (was a81b002).
Deleted feature/dashboard (was 923befa).

Upvotes: 1

Lucas
Lucas

Reputation: 14969

For powershell, this will work:

git branch --format '%(refname:lstrip=2)' --merged `
    | Where-Object { $_ -ne 'master' } `
    | ForEach-Object { git branch -d $_ }

Upvotes: 2

Ashish Yadav
Ashish Yadav

Reputation: 3196

To delete all local branches in linux except the one you are on

// hard delete

git branch -D $(git branch)

Upvotes: 54

user9547441
user9547441

Reputation:

Based on a combination of a number of answers here - if you want to keep all branches that exist on remote but delete the rest, the following oneliner will do the trick:

git for-each-ref --format '%(refname:short)' refs/heads | grep -Ev `git ls-remote --quiet --heads origin | awk '{print substr($2, 12)}'| paste -sd "|" -` | xargs git branch -D

Upvotes: 6

sblom
sblom

Reputation: 27363

To delete every branch except the one that you currently have checked out:

for b in `git branch --merged | grep -v \*`; do git branch -D $b; done

I would recommend changing git branch -D $b to an echo $b the first few times to make sure that it deletes the branches that you intend.

Upvotes: 72

kiewic
kiewic

Reputation: 16450

From Windows Command Line, delete all except the current checked out branch using:

for /f "tokens=*" %f in ('git branch ^| find /v "*"') do git branch -D %f

Upvotes: 21

Hunter
Hunter

Reputation: 2470

The below command will delete all the local branches except master branch.

git branch | grep -v "master" | xargs git branch -D

The above command

  1. list all the branches
  2. From the list ignore the master branch and take the rest of the branches
  3. delete the branch

Upvotes: 74

Related Questions