How do I quit Vim with a non-zero exit code?
Answer
:cq
Explanation
The :cq command quits Vim and returns a non-zero exit code to the calling process. This is invaluable when Vim is launched as a subprocess by another tool, such as git commit or git rebase -i.
Why it matters
When Git opens Vim for a commit message or interactive rebase, it checks Vim's exit code. If Vim exits normally (:q), Git proceeds. If Vim exits with an error (:cq), Git aborts the operation.
Common use cases
- Abort a
git commitafter Vim opens for the message - Cancel an interactive rebase mid-edit
- Bail out of
crontab -ewithout saving changes - Exit any tool that uses
$EDITORand checks the exit code
Example
" Git opens Vim for commit message
" You realize you're not ready to commit
:cq
Git sees the non-zero exit and prints:
Aborting commit due to empty commit message.
Tips
:cqtakes an optional exit code::cq 2exits with code 2- Unlike
:q!, which discards changes but exits successfully,:cqsignals failure to the parent process - This works even if you have unsaved changes — no need to add
!