Saving and Exiting Files
You have learned the vi command ZZ to quit and write (save) your file. But
you will frequently want to exit a file using ex commands, because these commands give you
greater control. We’ve already mentioned some of these commands in
passing. Now let’s take a more formal look:
:wWrites (saves) the buffer to the file but does not exit. You can (and should) use
:wthroughout your editing session to protect your edits against system failure or a major editing error.:qQuits the editor (and returns to the Unix prompt).
:wqBoth writes the file and quits the editor. The write happens unconditionally, even if the file was not changed.
:xBoth writes the file and quits (exits) the editor. The file is written only if it has been modified.[20]
vi protects existing files and your edits in the buffer. For example, if you want to write your buffer to an existing file, vi gives you a warning. Likewise, if you have invoked vi on a file, made edits, and want to quit without saving the edits, vi gives you an error message such as:
No write since last change.
These warnings can prevent costly mistakes, but sometimes you
want to proceed with the command anyway. An exclamation point
(!) after your command overrides
the warning:
:w! :q!
:w! can also be used to save
edits in a file that was opened in read-only mode with vi-R or view (assuming you have write permission for
the file).
:q! is an essential editing command that allows you to quit without affecting the original file, ...