Merge and delete branch in one step/command

GitMergeGit BranchBranching and-Merging

Git Problem Overview


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.

Git Solutions


Solution 1 - Git

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.

Solution 2 - Git

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 mg $1 && git br -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 forget the comment character (#) at the end of the alias! It will not work without it.

Solution 3 - Git

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBendEgView Question on Stackoverflow
Solution 1 - GitZbynek Vyskovsky - kvr000View Answer on Stackoverflow
Solution 2 - GitJacob LockardView Answer on Stackoverflow
Solution 3 - GitramwinView Answer on Stackoverflow