8

Let's say I have 3 unpushed commits. Now I want to change the commit message of the first or second commit (changing them for the third one is simple using git commit --amend). How to do that?

1
  • 1
    That is a bit similar to stackoverflow.com/questions/3926768/…. I tried (below) to see how a commit --amend could be scripted. Let me know if it works. Commented Oct 15, 2010 at 9:13

2 Answers 2

7

To rebound on the sub-question: is there a git commit --amend for a previous commit (and not just the last one), you could try something like (not tested yet, but Colin O'Dell mentions in the comments having written a script for it colinodell/git-amend-old):

git checkout -b tmp
git reset --hard HEAD~2
git commit -amend 
git rebase --onto tmp HEAD@{1} master

That would be like:

x---x---x---x---x
                ^
                |
               (master*) (* = current branch)

git checkout -b tmp
x---x---x---x---x
                ^
                |
               (tmp*, master) 

git reset --hard HEAD~2
x---x---x---x---x
        ^       ^
        |       |
      (tmp*) (master) 

git commit -amend 
      y (tmp*) 
     /
x---x---x---x---x
        |       ^
   (HEAD@{1})   |
          (master) 

git rebase --onto tmp HEAD@{1} master
    (tmp)
      y---x'---x' (master*) 
     /
x---x---x---x---x (only referenced in reflog)
Sign up to request clarification or add additional context in comments.

5 Comments

On the rebase --onto, see stackoverflow.com/questions/1994463/…
why bother? rebase -i is much simpler
@CharlesB: I agree, rebase -i is simpler, but it also interactive. Meaning you cannot include it in a script or in an alias grouping a sequence of commands.
I've created a Bash script inspired by this answer: github.com/colinodell/git-amend-old Hopefully somebody finds it useful.
@ColinO'Dell nice one! i have included a link to your script in the answer for more visibility.
6

This is a job for the powerful git rebase -i command. Also, see the Interactive Rebasing section of the Git book.

4 Comments

Maybe a stupid question, but can git rebase -i be used non-interactively?
No, not as such. However, everything that git rebase -i does can (in theory) be done using other, scriptable Git commands. So it would be possible to write a script to modify a previous commit message, but I don't know whether such a thing exists yet.
congrats on your 15th gold badge ;) You are now a true git! (Err... git-guru, I meant) (I mean, guru about the tool name git) (I mean, you know what I mean)
@VonC: Thanks, that one kind of snuck up on me!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.