258

I have asked Git to perform a commit from within git bash, It has brought up VI as it always does.

I now wish to cancel the commit, how do I prevent proceeding with the commit from this point?

Ben Aston
  • 53,718
  • 65
  • 205
  • 331

4 Answers4

403

You have two options:

  • Provide an empty commit message. If it's a new commit and you haven't yet saved the message, you can simply use :q! (quit without saving). If you’ve already saved (or you're amending a previous commit), just delete the entire log message and save again. This can be done with ggdG + :wq in Vim.

  • Have the editor exit with a non-zero exit code. In Vim, you can use :cq (quit with an error code).

It's worth noting that you can always reset your working copy to the state it was in before the commit with git reset HEAD^.

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
  • 140
    :cq is the business. For some reason git ploughs on regardless if i use :q! – Sirex Dec 18 '12 at 22:27
  • 3
    git reset HEAD^ would discard local modifications – juanmf Jun 09 '17 at 23:00
  • 5
    :q! probably doesn't work because there is a predefined message already there, you are just editing it. – Papipo Aug 16 '17 at 13:16
  • 1
    Hiccup: If `git reset HEAD^` asks for more, your shell may interpret ^ as line continuation. Try `git reset "HEAD^"`, `git reset HEAD^^`, or `git reset HEAD~1` instead per this answer: https://stackoverflow.com/questions/14203952/git-reset-asks-more – Jake Stevens-Haas Aug 06 '19 at 16:22
119
  • :q! does not work when amending a commit. It does not update the commit message, but it executes the amendment :-(
  • :cq completely aborts the amendment.
Daniel Pinyol
  • 2,094
  • 2
  • 15
  • 15
11

To sum up:

  • When creating a new commit (i.e git commit) quit using :q!.
  • When amending (i.e. git commit --amend) remove the commit message (only the first few rows not beginning with a #) for example by holding v and using arrow keys to select it and then pressing Delete. Quit with :wq to apply changes! If you use :q! the changes will be lost and the previous commit message will be used.

When using VIM it's ok in both cases to quit with :cq - VIM will quit with an error code and the commit will be aborted.

Maciej
  • 546
  • 4
  • 15
0

All answers are trying to teach you a bit of vim

but if you really have a problem closing a vim

you can have much more problems with the edition

and the situation will be repeated on every interaction in git

so you'd like to change a git editor

git config --global core.editor nano

git config --global core.editor <your_editor>

or learn editors like vim or emacs.

serv-inc
  • 35,772
  • 9
  • 166
  • 188
Sławomir Lenart
  • 7,543
  • 4
  • 45
  • 61