Git 202 - Squash Multiple Commits, Edit Last Commit, Git reset

Here we will go over some more advanced git scenarios.

Squah Multiple Commits

  1. Let’s say we have multiple commits and we want to squash them. We use rebase to the first commit. The rebase screen will come up.

    1
    2
    3
    b1 # commit 1
    b2 # commit 2
    git rebase -i 49687a0a646954afdf3f4dae1f914ea793341ea2 (Commit 1 version number)
  2. After rebase command we enter editor interface where we can edit the commits. Basically you need to choose one to squash and choose pick for the rest of the commits.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    pick 033beb4 b1
    pick d426a8a b2

    # Rebase 49687a0..d426a8a onto 49687a0
    #
    # Commands:
    # p, pick = use commit
    # r, reword = use commit, but edit the commit message
    # e, edit = use commit, but stop for amending
    # s, squash = use commit, but meld into previous commit
    # f, fixup = like "squash", but discard this commit's log message
    # x, exec = run command (the rest of the line) using shell
    #
    # If you remove a line here THAT COMMIT WILL BE LOST.
    # However, if you remove everything, the rebase will be aborted.
    #
  3. Next you need to enter a new commit message

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    b
    # This is a combination of 2 commits.
    # The first commit's message is:
    # b1
    #
    # This is the 2nd commit message:
    #
    # b2
    #
    # Please enter the commit message for your changes. Lines starting
    # with '#' will be ignored, and an empty message aborts the commit.
    # Not currently on any branch.
    # Changes to be committed:
    # (use "git reset HEAD <file>..." to unstage)
    #
    # modified: a.txt
    #
  4. You can check git log for update

Edit last Comment

  1. You use the amend command. Ammend command go back to the previous commit and edit it.
  2. Another way is revert, which creates a new commit (does not interfere previous commit) but reverts status to previous commit.

    1
    2
    git commit --amend -m "New commit message"
    git revert <version number>

Git Reset

Here are some commands when you want to return to previous commit or situation before merge.

1
2
3
4
5
6
# return to previous commit
git reset HEAD^ --hard
# return to previous commit or cancel merge when enter conflict
git reset --hard
# after merge return to before merge
git reset --hard ORIG_HEAD