Can I delete all the local branches except the current one?

后端 未结 14 2316
广开言路
广开言路 2020-12-12 13:07

I want to delete all branches that get listed in the output of ...

$ git branch

... but keeping current branch, in one step. Is th

相关标签:
14条回答
  • 2020-12-12 13:30

    Assuming git branch shows the current branch prefixed with *; Using Powershell the following one liner will delete all branches that don't start with *.

    git branch | ? { $_ -lt "*" } | % { git branch -D $_.Trim() }

    ? = Where-Object

    % = Foreach-Object

    0 讨论(0)
  • 2020-12-12 13:33

    first (switch to the branch you want to keep > ex: master):

    git checkout master
    

    second (make sure you are on master)

    git branch -D $(git branch)
    
    0 讨论(0)
  • 2020-12-12 13:34

    To remove all merged branches(except current -v ‘*’):

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

    also I made such command for repo complete clean up:

    alias git-clean="git branch  | grep -v '*' | grep -v 'master' | xargs git branch -D  && git reset --hard && git clean -d -x -f"
    

    taken from here.

    0 讨论(0)
  • 2020-12-12 13:36
    $ git branch | grep -v "master" | xargs git branch -D 
    

    will delete all branches except master (replace master with branch you want to keep, but then it will delete master)

    0 讨论(0)
  • 2020-12-12 13:36

    I once created this construct for my Windows environment. Maybe it'll help someone else. During execution, the master and current branch are not deleted. All other merged branches will be deleted regardless.

    @echo off
    cd PATH_TO_YOUR_REPO
    
    REM -- Variable declerations
    set "textFile=tempBranchInfo.txt"
    set "branchToKeep=master"
    set "branchToReplaceWith="
    git branch --merged > %textFile%
    
    REM -- remove "master" from list to keep the branch
    for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        >>"%textFile%" echo(!line:%branchToKeep%=%branchToReplaceWith%!
        endlocal
    )
    
    REM -- execute branch delete commands
    for /f "delims=" %%a in (%textFile%) do (
        git branch -D %%a
    )
    
    REM -- remove temp-file with branch information inside
    DEL %textFile%
    
    REM -- show local branches after the cleaning
    echo Local branches:
    git branch
    
    pause 
    exit
    
    0 讨论(0)
  • 2020-12-12 13:36

    Delete all merged branch locally:

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

    Delete all branches except a specific branch:

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

    Delete all local branches except develop and master

    git branch | grep -v "develop" | grep -v "master" | xargs git branch -D
    
    0 讨论(0)
提交回复
热议问题