69

Is it possible, to merge a branch and automatically delete it with a single command? The delete step should only be executed if merging was successful.

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
BendEg
  • 20,098
  • 17
  • 57
  • 131

3 Answers3

113

No, git doesn't support this at the same time.

However, you can run the commands in a shell conditionally:

git merge source-branch && git branch -d source-branch

Edit:

-d will only remove merged branches while -D will also remove unmerged branches, so -d will ensure that the branch is merged and you don't delete a branch by accident.

Tobias Helbich
  • 447
  • 14
  • 32
Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43
  • 1
    For me `-d` refuses to merge branches not merged in origin so I also need to do: `git push --delete origin source-branch` before I an apply this solution. – Calimo Dec 11 '18 at 15:03
  • 4
    `git push origin --delete source-branch` to also delete on origin. – Roland Puntaier Jan 17 '22 at 08:57
17

This is an old question, but for those who stumble upon it looking for this functionality, you can now add a Git alias to accomplish this. For example, in .gitconfig:

# ...

[alias]
  mgd = "!git merge $1 && git branch -d $1; #"

Then, you could run git mgd branch-name to merge and delete a branch in one go. Note that the lowercase -d flag ensures that the branch will only be deleted if it has already been fully merged; thus, you don't have to worry about the first command not working correctly and then losing the branch.

The exclamation point at the beginning of the alias signifies that this is a bash command, and $1 stores the argument that the user passed in (i.e. the name of the branch to merge/delete).

NOTE: Do not leave out the comment character (#) at the end of the alias! It will not work without it. (Why?)

Jacob Lockard
  • 1,195
  • 9
  • 24
  • Wouldn't the expansion of "git mgd branch-name" result in `!git git mg branch-name && git br -d branch-name; #` – A. Rick Oct 28 '20 at 13:04
  • 1
    @A.Rick Actually, no, because the exclamation point signifies that the alias should be run as a bash command. Thus, only the command is run, without `git` prefixed. – Jacob Lockard Dec 19 '20 at 16:38
3

I will write a script.

git branch | grep -v master | xargs git merge &&
git branch | grep -v master | xargs git branch -d

Here the branch name master can be replaced by your current branch name.

Don't forget the &&. If the first line fails then the second is not executed.

jiwopene
  • 3,077
  • 17
  • 30
ramwin
  • 5,803
  • 3
  • 27
  • 29