So, on stock Mac OSX Yosemite, if I run vi /tmp/foo and then type in some text, and finally do :Wq (a common typo I make) and then :wq. Everything will appear to be fine, but for some reason the exit code will be 1. If I repeat the same thing, but don't do :Wq then it returns 0.

This is maddening for git commit where I'll type in a commit message, make this mistake and suddenly lose my commit message because git things vi didn't write the file

How can I fix this behavior to not happen anymore and always return 0 unless there is a real error with writing the file?


This is done intentionally in vim:

  • the ":wq" command calls, ex_exit,
  • which calls getout with a nominal exit-code 0,
  • in getout, it checks for an error in ex-mode, commenting
    /* When running in Ex mode an error causes us to exit with a non-zero exit
     * code.  POSIX requires this, although it's not 100% clear from the
     * standard. */
    if (exmode_active)
        exitval += ex_exitval;
  • the ex_exitval variable is set by the error-message in emsg:
    called_emsg = TRUE;
    if (emsg_silent == 0)
        ex_exitval = 1;
  • and ex_exitval is never cleared.

So "any" error message in ex-mode (the : commands) will produce this result. A quick check shows that the vi-mode ZZ also is affected by ex-mode error-messages.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.