Vim or Vi is the most advanced text editor designed for command-line usage. Vim with its predecessor Vi provides a lot of features that are more than a GUI-based text editor. When you complete the job on a file you generally save the file and exit or quit. Vim provides easy-to-use shortcuts and commands for practical file save and quit.
Open File with Vim and Vi
First, we will open our file named test.txt from the command line by providing the file name. The cursor will be at the start of the file.
$ vim test.txt
Save File and Quit with :wq Command
The most practical and popular way to save a file and quit from Vim is using the :write
and :quit
commands.
- Press ESC to change normal mode.
- Type :write which will save the current changes.
:write
- Type :quit which will close the file and quit from the Vim.
:quit
As stated previously Vim is a very practical command line text editor and provides an easier way where the write and quit commands will be abbreviated as wp.
- Press ESC to change normal mode.
- Type :wq which will save the current changes.
:wq
Save File and Quit with ZZ Keys
In the previous part, we used the write and quit commands and their abbreviated version wp. Also, Vim uses ZZ keys in order to save the current file changes and exit from Vim. Keep in mind that Z is uppercase.
- Press ESC to change normal mode.
- Press ZZ keys which will save the current file changes and exit from vim.
ZZ
Save File with Different Name and Quit
As you expect by default the save operation will save the file with the same named it is opened. But in some cases, you may want to save the file with a different name and then quit. We will use the write and quit commands. Also, we will provide the new file name into the write command as a parameter.
- Press ESC to change normal mode.
- Type :write “NewFile.txt” where the new file name is NewFile.txt
:write NewFile.txt
- Type :quit or :q in order to exit.
:quit
Quit Without Saving File
In some cases, you may need to exit without saving the file. These actions will not save the changes after the last save or file opens. We will add the ! sign at the end of the quit or q command like below. Keep in mind that this lost all recent changes that are not saved into the file.
- Press ESC to change normal mode.
- Type :q! or :quit! and then Enter.
:quit!
Exit vim By Killing It
Up to now, we have examined royal and natural ways to exit vim without saving content. The extraordinary way of existing vim without saving changes is killing the vim process with the pkill
command. The pkill command kills all processes with the specified name and this will lost the changes and the file is closed.
$ pkill vim