LoginSignup
1
0

More than 5 years have passed since last update.

gitのブランチを正規表現でマッチしたものだけ一括削除

Last updated at Posted at 2019-01-14

gitの機能として、複数ブランチの一括削除はできない。

なので、わたしは正規表現で、ブランチ名をマッチさせて、マッチしたブランチを確認した上で、削除するようにしている。
それのbashscriptが下記の通りで、わたしは、~/.bash_profile に追加して利用している。

script (bash)


function rmbranch () {
    if [ -z "$1" ] ; then
        echo -e "ブランチ名を正規表現で入力してください. \nex)\n\$ rmbranch feature/practice.+"
        return 1
    fi

    rmTargets=`git branch | egrep "$1"`

    if [ -z "$rmTargets" ] ; then
        echo "削除対象ブランチがないため処理を終了します."
        return 0
    fi

    echo "削除対象ブランチ:"
    echo $rmTargets
    echo "----------------------------"
    echo "ブランチ削除を実行しますか?"
    echo "  実行する場合は y、実行をキャンセルする場合は n と入力して下さい."
    read input

    if [ -z $input ] ; then

        echo "  y または n を入力して下さい."
        rmbranch

    elif [ $input = 'yes' ] || [ $input = 'YES' ] || [ $input = 'y' ] ; then

        echo "  削除を実行します."
        git branch | egrep "$1" | xargs git branch -D

    elif [ $input = 'no' ] || [ $input = 'NO' ] || [ $input = 'n' ] ; then

       echo "  処理をキャンセルしました."
       return 1

    else

        echo "  y または n を入力して下さい."
        rmbranch

    fi

    return 0
}

使い方

例えば、ブランチがこんな感じになっていたとして、

terminal
$ git branch
  feature/practice1
  feature/practice2
  feature/practice3
  feature/practice4
  feature/practice5
* master

先頭が feature/practice のブランチを全て削除する場合は、下記のように rmbranch feature/practice.+ とターミナルで入力する。

terminal
$ rmbranch feature/practice.+

すると、削除対象のブランチが表示される。

terminal
削除対象ブランチ:
feature/practice1 feature/practice2 feature/practice3 feature/practice4 feature/practice5
----------------------------
ブランチ削除を実行しますか?
  実行する場合は y、実行をキャンセルする場合は n と入力して下さい.

ここで、y を入力すると、削除対象ブランチが削除される。

terminal
$ rmbranch feature/practice.+
削除対象ブランチ:
feature/practice1 feature/practice2 feature/practice3 feature/practice4 feature/practice5
----------------------------
ブランチ削除を実行しますか?
  実行する場合は y、実行をキャンセルする場合は n と入力して下さい.
y
  削除を実行します.
Deleted branch feature/practice1 (was e83a435).
Deleted branch feature/practice2 (was e83a435).
Deleted branch feature/practice3 (was e83a435).
Deleted branch feature/practice4 (was e83a435).
Deleted branch feature/practice5 (was e83a435).

n を入力すると、ブランチは削除されない。

terminal
# n を入力した場合

$ rmbranch feature/practice.+
削除対象ブランチ:
feature/practice1 feature/practice2 feature/practice3 feature/practice4 feature/practice5
----------------------------
ブランチ削除を実行しますか?
  実行する場合は y、実行をキャンセルする場合は n と入力して下さい.
n
  処理をキャンセルしました.
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0