Saving a File in vi
vi offers features similar to the familiar Save and Save As features found in most Macintosh applications.
To begin, you must be in command mode. All save commands in vi begin with a colon . This drops the cursor to the last line of your Terminal window and tells vi you are about to enter a command that affects the entire file.
You will see that many vi commands begin by the user 's typing a colon ( : ). If the cursor doesn't drop to the status line when you type a colon, then you have forgotten to switch to command mode. In those cases, delete (press ) the colon you inserted and press .
You always press at the end of vi commands that start with a colon.
To save the current file:
The :w command (for write to disk ) saves the current file. If you do not supply a filename, your changes will be saved to disk in the temporary file that, unbeknownst to you, vi was already using.
To save the file with a new filename:
- :w pathname
The current version of the file is saved at pathname .
You are still "in" the file you started on after the save; that is, using :w pathname doesn't change which file you are editing.
Usually the pathname is simply a filename to save the file in the current directory, but there is no reason why you cannot save to a file somewhere else; you just have to supply a proper (relative or full) pathname. For example,
:w ~/Documents/ newfile.txt
saves a copy of the file you are editing as newfile.txt in the Documents directory of your home directory, regardless of where you were when you started vi .
To save and attempt to override warnings:
Sometimes you get warnings that vi is unable to save a file when you use the :w command. Often the problem is related to the file's permissions that is, who has permission to read, write, and copy it (we'll cover permissions in detail in Chapter 8, "Working with Permissions and Ownership"). As long as you either own the file or have write permission in the directory containing the file, using :w! will override permission warnings.