Suppose I was on master
branch and created a new branch:
git checkout -b feature_branch
I started to work on feature_branch
, and at some point I would like to merge my changes to master
using rebase. So, I do:
# Get the latest code on master
git checkout master
git pull
# Rebase on master and push the most updated 'feature_branch'
git checkout feature_branch
git rebase master
git push
# Merge 'feature_branch' to 'master' and push the updated 'master'
git checkout master
git merge feature_branch
git push
# Back to work on 'feature_branch'
git checkout feature_branch
Is there a way to reduce the number of steps and achieve the same?
At the end of the process I would like master
, origin/master
, feature_branch
, and origin/feature_branch
, to point to the same commit.
You can remove a couple commands. This does the same:
# you have to have the branch checked out to pull, since pulling means merging
# into master, and you need a work tree to merge in
git checkout master
git pull
# no need to check out first; rebase does the right thing with two arguments
git rebase master feature_branch
git checkout master
git merge feature_branch
# git push by default pushes all branches that exist here and on the remote
git push
git checkout feature_branch
Strictly speaking, the merge into master is guaranteed to be a fast-forward (a trivial merge), so it doesn't actually need a work tree, but there's not really a built-in way skip the checkout. There are workarounds, e.g. pushing into the same repository: git push . feature_branch:master
(safe, but weird) or directly updating the ref: git update-ref master feature_branch
(unsafe - doesn't check if it's a fast-forward) but generally you might as well just quickly switch branches.
Also note that if you didn't want to rebase the feature branch, you could just skip that, not rewrite feature_branch, and end up with a merge commit in master instead of the rebased feature_branch and fast-forward merge.