Skip to content

Instantly share code, notes, and snippets.

@desaiuditd
Last active August 20, 2021 10:31
Show Gist options
  • Save desaiuditd/fefc1e0aaa64b781b074a286b04f79ac to your computer and use it in GitHub Desktop.
Save desaiuditd/fefc1e0aaa64b781b074a286b04f79ac to your computer and use it in GitHub Desktop.
Git Squash Commits and Change Timestamp

Let's say, 5 commits are made in develop branch.

  • Commit 4 => 2017/06/23
  • Commit 3 => 2017/06/22
  • Commit 2 => 2017/06/21
  • Commit 1 => 2017/06/20

Now we want to squash these commits into one commit (i.e., the latest commit on 2017/06/23).

git rebase -i HEAD~4

Here it's 4 because there are 4 commits.

By default, git rebase lets you squash upto previous commit. This means, by default, the above command can squash Commit 4, Commit 3 & Commit 2.

We can choose what we want to do with each commit.

# 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
# d, drop = remove commit

So we can't do directly,

  • p Commit 4 => 2017/06/23
  • s Commit 3 => 2017/06/22
  • s Commit 2 => 2017/06/21
  • s Commit 1 => 2017/06/20

Because we have to choose a previous commit.

Hence, what we will do is as follows:

  • s Commit 4 => 2017/06/23
  • s Commit 3 => 2017/06/22
  • s Commit 2 => 2017/06/21
  • p Commit 1 => 2017/06/20

So it will squash all the commits into Commit 1 => 2017/06/20. If we want to change the commit message of Commit 1, then choose r - reword instead of p - pick.

And then we will change the commit timestamp of Commit 1. This can be done as follows:

GIT_COMMITTER_DATE="`date`" git commit --amend --date "`date`"

This set the commit timestamp as current timestamp. If you want specific date then run the command as follows:

GIT_COMMITTER_DATE="Wed Feb 16 14:00 2011 +0100" git commit --amend --date="Wed Feb 16 14:00 2011 +0100"

@Radon8472
Copy link

Radon8472 commented May 22, 2019

you could also do:

p Commit 1 => 2017-06-20
s Commit 2 => 2017-06-21
s Commit 3 => 2017-06-22
s Commit 4 => 2017-06-23
x git commit --amend -c [Commit-Hash From "Commit 4"]

It works fine, the only problem is that you have to re-insert the commit-message when you have a combined message for all 4 commits

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment