简体   繁体   中英

How to make a small fix of an old commit when I haven't pushed yet?

For example one commit I have added a .gitignore file. I have done some work after that, but now realized that I should have add one more folder that I should ignore at that time.

mybranch HEAD 1: Much work 2: Much work 3: Add .gitignore origin/master 4: Others have this

I do not want to make a new commit that says "Edit .gitignore" but rather go back and fix that. Since I haven't pushed my commits to others yet I would like to tidy up my commits as much as possible.

I figured I might have to check out that commit and amend it. Then how can I repeat the newer commits? Doing merge one by one to the final point would make me ended up on a new branch. I would like to end up like the starting point minus the small change.

You might want to use rebase and squash commits into one.

Assuming you want to squash your last two commits into one commit:

$ git rebase -i HEAD~3

Now you should have something like:

pick ccccccc third commit
pick bbbbbbb second commit
pick aaaaaaa first commit

# Rebase ...... onto ......
#
# 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
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

Replace pick with squash (or simply s ) on whatever commits you want to squash into one.

For more detailed explanation, go through the link posted above.

What you can do is introduce a new commit, with the change to .gitignore , and then move and squash it into the old commit.

After the new commit you'll have

HEAD 1: .gitignore edit
2: Much work
3: Much work
4: Add .gitignore
...

Then if you run git rebase -i HEAD~4 you'll be presented with the commits in an editor and have to choose which to keep. You can move the new [1] to right after [4], and set it to squash instead of pick , which would make it "meld into previous commit".

You can read more about this process here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM