How to save and quit in Vi/Vim Editor.
Vi is an advanced and very powerful text editor that works in CLI only mode. Vim is a modified and newer version of Vi and is absolutely backwards compatible with it. You might hear both these names these days: Vi or Vim, so don’t be confused and know that they are referring to the same editor.
It’s preinstalled on almost any Linux distribution and is a go-to editor when you have only CLI access to the machine.
Some new users find using it a bit confusing when they start using it. Even such a simple task as saving and quitting the editor is a bit tricky, so let’s have a look at the options.
Vi/Vim has three modes: Normal, Insert and Visual. Usually you type the text in Insert mode, and perform all other control operations(e.g. delete, cut, copy, paste, search, save the file or quit) in Normal mode. Visual mode is used for highlighting and selecting text.
When you open a file you are placed into Normal mode and if you want to start typing you need to press “i” which will put you into Insert mode. To go back to Normal mode press “Esc” key on the keyboard. Commands in Normal mode start with “:” (colon) symbol as you will see in examples below.
How to save the file without quitting the editor?
To save the file without quitting the editor make sure you are in Normal mode by pressing “Esc” and then press “:” followed by “w”. You will see the command will appear at the bottom of the editor window:
Then press Enter and the command will run and save the file. Then you can press “i” to return to Insert mode so you can continue typing the text.
How to save the file with a different file name?
It’s also possible to save the file with a different name, in this case the command will be “:w new_file.txt”
Be aware that after you save the file with a different name you still continue editing the original one – it will not switch automatically to the new file.
How to save the file and quit the editor?
If you want to save the file and quit in one command then switch to Normal mode (press “Esc” to do that) and type the command “:wq” and then press Enter. This will save the changes and exit the editor:
How to exit the editor and discard changes?
To exit the editor enter “:q” command, but if you have any unsaved changes you will need to explicitly tell the editor that you want to discard them by prepending “!” to the command:
If you forget to add “!” you will get the error as shown below, which is nice, because it prevents accidental data loss:
Hope these tips were helpful. Vi/Vim Editor might be a bit confusing and intimidating at first, but over time it will become very powerful and useful tool in your toolkit.