Learn Git - Interactive Rebase, Squash Commit

Question Click to View Answer

Make a directory called interactive_rebasing and change into the directory.

$ mkdir interactive_rebasing
$ cd interactive_rebasing

Execute the following commands. Then create a branch called messy.

git init
touch a_file
echo 11111 >> a_file
git add a_file
git commit -m "initial commit"
echo 222222 >> a_file
git commit -am "feature 1"
echo lalalalala >> a_file
git commit -am "feature 2"
git checkout -b messy

Run the following commands on messy and look at the git history. Describe the best way to push the messy feature branch to master.

echo blah >> a_file
git commit -am "fixed a typo"
echo meow >> a_file
git commit -am "wrote some code"
echo done >> a_file
git commit -am "finished messy feature"

Use $ git log to view the branches in terminal or $ gitk to view the changes with a graphical interface. The git history was clean until the messy feature branch. It would be great to consolidate all the commits on the messy branch into one and then merge it with master for a clean commit history.

Take the first step to merging the three commits on the messy branch into one.

$ git rebase -i HEAD~3

Update the file as below and then save and quit. pick 0e84034 fixed a typo s d87b9b8 wrote some code s 4cf3897 finished messy feature

Use HEAD~3 because we are merging the last three commits. s stands for squash

Update the file that opens up automatically when the file from the previous step is saved and closed.

Delete the contents of the file and add the following line: Add feature 3. Save and quit.

View the git log after interactive rebasing is completed. Confirm that the file still has the changes from the commits on messy branch.

$ git log

Run the following command to see all the changes are still intact.

$ cat a_file

Apply the commit from the messy branch to master.

$ git checkout master
$ git merge messy