git: Merge A Range of Commits from One Branch to Another

Suppose we have created two branches, namely master and work, we developed a few features and fixed a few bugs on the work branch, and we want to merge the bug fixes to the master branch. Below are the steps that should be carried out.

0. Check out the commits range

Make sure we’re at work branch. We can use either “git log” or a GUI tool like gitk to see what are the start and end commit SHA1 IDs. Below is a sample output of “git log”.

Suppose we want to merge the first two commits from the work branch to master branch. The SHA1 ID are 315125… and 46e768… respectively.

1. Check out a temporary branch

This can be done with the command below,

git checkout master
git checkout -b tmp

This branch tmp will be the same as master branch. And now we’re at tmp branch.

2. Move work branch ahead

This can be done with the following command,

git branch -f master 315125

We only need to provide the first few digits of the SHA1 ID, git is smart enough to figure it out the rest. This will set the master branch to contain all the commits up to commit 315125.

3. Rebase

This is done with command below,

git rebase –onto tmp 46e768~1 master

46e768 is the start commit number we want to merge to master branch. This will rebase master branch to tmp branch + all commits between 46e768 and 315125. Since tmp branch contains the what the original master branch contains. This is equivalent to adding commits from 46e768 to 315125 to master branch.

In case there’s any conflicts, we’ll need to resolve the conflict and run

git rebase –continue

After it’s done, we’ll be at master branch, ready to push the changes.

Publish Git Repository to Server

At times we’ll need to create a git repository and put is to a server where other developers can access. Of course you can do it with github or other git repository hosting service, but what if you’ll need to put it to your own server?

1. Create git directory locally

1.a to make your current directory a git repository, enter the command,

git init

1.b to make a directory a git repository, enter the command,

git init <directory name>

After initialization the git repository, you can add some files. If the repository is empty when you publish to server, it’ll more troublesome to configure.

2. Add new files

git add <project files and folders>
git commit -am “check in msg”

3. Publish repository to server

git clone <directory path>/<directory name> <project name>.git
scp -r <project name>.git <ssh username>@<ssh server address>:<your git server path>

4. Commit changes to server

git push <ssh username>@<ssh server address>:<your git server path>/<project name>.git

or simply

git push

5. Clone the project

git clone <ssh username>@<ssh server address>:<your git server path>/<project name>.git

6. Get Changes

git pull <ssh username>@<ssh server address>:<your git server path>/<project name>.git

or simply

git pull