talabes
talabes

Reputation: 5484

How to rename last N commits messages in git?

I have 30 commits and I want to add "Bug XXXXXXX" at the beginning of all the messages, can I do this in a single action/command?

I'm trying to avoid squashing them.

Upvotes: 32

Views: 18961

Answers (3)

user26772667
user26772667

Reputation: 11

I believe I found the simplest way to do it:

  • one-shot
  • using only git
  • no filter-branch
  • not using reword which requires manual work

You can use the interactive rebase to amend each commit message individually:

  1. Initialize interactive rebase
    git rebase -i HEAD~N
  2. git-rebase-todo file should open.
  3. After each commit that You want to rename insert an exec command like so:
    pick c5e7fc5 Commit message 1
    exec git commit --amend -m "Modified commit message 1"
        
    pick 9e09de0 Commit message 2
    exec git commit --amend -m "Modified commit message 2"
  1. Finally close the file, allowing the rebase to run. If errors occur you have to deal with them as in normal rebase.

This allows You to change the problem into a text editing challenge.

Which I leave as exercise to the reader ;-)

Upvotes: 1

Sudeep Shakya
Sudeep Shakya

Reputation: 101

It might be better not to depend on either of the following:

echo -n "Bug XXXXXXX: "

echo "Bug XXXXXXX: \c"

The behavior of echo is dependent on which version of echo is being used. See the linked stackoverflow question below:

'echo' without newline in a shell script

A better solution might be:

git filter-branch -f --msg-filter '
    printf "%s" "Bug XXXXXXX: "
    && cat
    ' HEAD~<N>..HEAD

Upvotes: 2

Mark Mikofski
Mark Mikofski

Reputation: 20208

Use git rebase -i HEAD~<N> where N is the number of commits to go back, and -i will make it interactive, ie it will open in vim or whatever your default editor is. See Scott Chacon's Book. Then you can change the commit message.

If you need it automated, then you may need to try filter-branch:

another history-rewriting option that you can use if you need to rewrite a larger number of commits in some scriptable way

In this case you would use:

git filter-branch --msg-filter <command>

See man git-filter-branch

Here is the example given in the manual to append "Acked-by" to a range of commits. You can change it to "BUG XXXXXXX"

git filter-branch -f --msg-filter '
    echo "Bug XXXXXXX: \c"
    && cat
    ' HEAD~<N>..HEAD

where N is the number of commits to go back and append "BUG XXXXXXX"

Upvotes: 51

Related Questions