🔥

Git いらないブランチを一括で削除したい

2022/11/16に公開約1,100字

小ネタ

スクリプト

.bashrcや.zshrcなど
function git-clean() {
    PATTERN=`echo main master $@ | sed -e 's/ /|/g'`
    for branch in $(git branch --format='%(refname:short)'); do
        if [[ ! $branch =~ "^($PATTERN)$" ]]; then
            echo "$branch ?[y|N]"; read res
            if [ -z "$res" ] || [ $res = "y" ]; then
                git branch -D $branch
            fi
        fi
    done
}

function git-clean-force() {
    PATTERN=`echo main master $@ | sed -e 's/ /|/g'`
    for branch in $(git branch --format='%(refname:short)'); do
        if [[ ! $branch =~ "^($PATTERN)$" ]]; then
            git branch -D $branch
        fi
    done
}

main(or master)以外を削除したい

$ git branch         
  bar
  baz
  foo
* main

使用例

$ git-clean
bar ?[y|N]
y
Deleted branch bar (was 3d75d90).

baz ?[y|N]
y
Deleted branch baz (was 3d75d90).

foo ?[y|N]
y
Deleted branch foo (was 3d75d90).

確認なし

$ git-clean-force    
Deleted branch bar (was 3d75d90).
Deleted branch baz (was 3d75d90).
Deleted branch foo (was 3d75d90).

foo以外を削除したい

$ git-clean-force foo
Deleted branch bar (was 3d75d90).
Deleted branch baz (was 3d75d90).

Discussion

ログインするとコメントできます