Vi and Vim, as all of you know, have many synonyms. There are three ways I know of to save the file and exit Vim and Vi. These are :wq <cr>, :x <cr> and ZZ. I have heard that these are different in some way.

Are there any practical differences between using:

:x<cr>

:wq<cr>

or

ZZ

to save file and exit Vim and Vi?

  • The simple answer: they are the same. – JJoao Dec 5 '15 at 0:28
  • 2
    They are not the same. I don't know the difference exactly, but it is something about writing vs. not writing to the file if no changes have been made (i.e. updating the timestamp). – Wildcard Dec 5 '15 at 1:26
  • Also, from a practical point of view, ZZ (or ZQ) is shorter and easier to type ... – VanLaser Dec 5 '15 at 8:45
  • :help :wq, :help ZZ, :help :x. It's right there in the docs. – Antony Jul 11 '16 at 6:52
up vote 31 down vote accepted

From Vim's documentation, :x and ZZ are equivalent; they only save the file if it has been modified, then quit Vim:

Write current file, if modified, and quit (same as ":x").  
(Note: If there are several windows for the
current file, the file is written if it was modified and the window is closed).

:wq on the other hand writes the file and quits Vim (assuming proper permissions).

As akshay pointed out, Vim's documentation explains, that :x and ZZ are equivalent and only save a file if the associated buffer has been changed. Whereas :wq saves the buffer to the corresponding file, even if it is unchanged.

In both cases, the contents of the buffer will be saved to disk. Obviously the outcome is the same, so why bother, right? But wait... There is a subtle, but not irrelevant difference.

If you exit Vim via :x and there has been no change to the buffer, there will be no change to the modification time of that file. On the other hand, if you quit via :wq, the modification time will change, as the file is technically rewritten (saved again).

This can have some impact in certain situations. For example a backup process that is dependent on modification time, could store this file (and potentially send it over the network) even if no additional information has been included. Or some monitoring process could ring an alarm if it detects that (for it) the file has been changed...

Edit: I forgot to mention, in order to leave an modified buffer/file without changing the modification time, a :q (without the w) will work, too.

  • Also, some autocommands will run only when the file is written. They won't run if the file hasn't changed and Vim is quit with ZZ or :x. – Spidey Aug 18 at 20:46

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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