How To Save File and Quit In Vim/Vi?

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
Open File with Vim and Vi

Save File and Quit with :wq Command

The most practical and popular way to save a file and quit from the Vim is using the :write and :quit commands.

  • Press ESC to change normal mode.
  • Type :write which will save the current changes.
  • Type :quit which will close the file and quit from the Vim.

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.

Save File and Quit with ZZ Keys

In the previous part, we have 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.
READ  How To Use SFTP Command to Securely Transfer Files and Folders?

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
  • Type :quit or :q in order to exit.

Quit Without Saving File

In some cases, you may need to exit without saving the file. These actions will do 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.

  • Press ESC to change normal mode.
  • Type :q! or :quit! and then Enter.

Leave a Comment