To modify the previous commit I can run the commit on my staged changes
git commit --amend --no-edit
git push -f
The commit has been modified but the timestamp of the commit changes...
Is there a way not to change the timestap?. Something like:
git commit --amend --no-edit --no-time-change
Note that git commit --amend
does not modify a commit; instead, it makes a new-and-improved commit and stops using the old-and-lousy one. This distinction matters if anyone else, or any other branch, has access to the original commit, because they won't switch over to the new-and-improved commit. The new commit has a new and different hash ID; all the users of the old commit are using the old hash ID, which is unchanged. For these reasons, the fact that the date changes is usually unimportant.
That said: There are two timestamps in each commit:
When using git commit
, with or without --amend
, you can use --date=<whatever>
to specify the author date, but there's no flag for specifying the committer date.
Fortunately, there are two environment variables that you can set that override both committer and author dates. These are GIT_AUTHOR_DATE
and GIT_COMMITTER_DATE
. They accept the same date formats that --date
accepts, and that git show --pretty=fuller
shows for both the dates, for instance.
Using either eval
(which is a bit dangerous in general) or env
, we can have sh/bash-compatible shells do this for us as a one-liner:
eval $(git log --no-walk --format='GIT_AUTHOR_DATE="%ad" GIT_COMMITTER_DATE="%cd"') git commit --amend
or:
env GIT_AUTHOR_DATE="$(git log --no-walk --format=%ad)" GIT_COMMITTER_DATE="$(git log --no-walk --format=%cd)" git commit --amend
The eval
method is a bit shorter and invokes git
fewer times but does mean you must be careful about the command itself. As long as the command itself is just git commit --amend
, the whole thing works well, so you could make this a Git alias (remember the leading !
to force Git to pass it to a shell).
(Replace --no-walk
with -1
if you like. Note that either way we're relying on the fact that without a starting point, git log
assumes HEAD
.)