home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomeLearning the vi EditorSearch this book

5.3. 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.

:w
Writes (saves) the buffer to the file but does not exit. You can (and should) use :w throughout your editing session to protect your edits against system failure or a major editing error.

:q
Quits the editor (and returns to the UNIX prompt).

:wq
Both writes the file and quits the editor. The write happens unconditionally, even if the file was not changed.

:x
Both writes the file and quits (exits) the editor. The file is written only if it has been modified.[17]

[17]The difference between :wq and :x is important when editing source code and using make, which performs actions based upon file modification times.

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, regardless of any changes you made in this session. The contents of the buffer are discarded.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.