26

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.

Vertexwahn
  • 7,709
  • 6
  • 64
  • 90
talabes
  • 5,344
  • 2
  • 22
  • 27

2 Answers2

45

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"

Mark Mikofski
  • 19,398
  • 2
  • 57
  • 90
  • 2
    I would like to avoid stopping after each commit I want to modify and change the message... – talabes Jan 07 '13 at 18:08
  • here's a [list of SO's recent filter branch questions](http://stackoverflow.com/questions/tagged/git-filter-branch) – Mark Mikofski Jan 07 '13 at 18:12
  • Nice solution! Just one thing before setting this answer as solution, the messages are now: "Bug XXXX: \n ", how can I leave the whole new message in one line? Thanks! – talabes Jan 07 '13 at 18:50
  • Try `echo -n "Bug XXXX: " && cat` to avoid the trailing newline. Does that work? – Mike Seplowitz Jan 07 '13 at 18:54
  • Nope...it prints: "-n Bug XXXX: \n ". Weird, because only Bug XXX is between "". – talabes Jan 07 '13 at 18:58
  • 2
    "git filter-branch -f --msg-filter 'echo "Bug XXXXXXX: \c" && cat' HEAD~N..HEAD" is the final answer :) – talabes Jan 07 '13 at 19:02
2

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
Sudeep Shakya
  • 101
  • 1
  • 4