1. Introduction

Vim is a powerful tool distributed with most Linux and Unix systems, including macOS. Whether an editor of choice or a quick way to write git commit descriptions, at times it can be quite confusing.

In this article, we will decipher the basics everyone should know: how to save and quit.

2. Save and Quit

First, let's assume we already know how to open a file and edit it. Vim, by default, starts in normal mode, also known as command mode. This mode is where we will be writing our commands. We can use the Esc key to switch from insert mode back to normal mode.

When we open a file, Vim creates a buffer. In essence, this is a temporary copy of the file's contents. Thus, to save our changes we override the original file with this buffer. The :w command, a shorthand version of :write, will do exactly that:


Perhaps, we may want to save the buffer to a different file. We could also be working with a buffer that is not associated with any file. In these cases, the destination path can be provided as an argument. It can be an existing file or a new one we wish to create:

:w {file path}

Now, that we have saved our changes, we may want to exit. The :q command, a shorthand for :quit, quits the current buffer:


Assuming we are working with one file or buffer, that will also quit the application.

Vim gives a helpful warning and terminates the action if anything goes wrong. Attempting to quit when we have unsaved changes is one such scenario. Another is opening the file in read-only mode and then deciding to modify and save it. In both cases, we can force the action with a trailing !:


Note, although ! in our context forces the action, it does not have universal meaning in Vim.

3. Combining Commands

The :wq command will do save and quit together:


The scenarios separately discussed for saving and quitting can happen here as well. For example, we will need to provide a destination file path when we attempt to save an unnamed buffer:

:wq {file path}

Likewise, when we need to make modifications after opening the file in the read-only mode, we can force save and quit:


There is another useful command. The :x command, a shorthand for :xit or :exit, will also save and quit:


However, there is one key difference. Unlike :x, the :w and :wq commands will change the last modification date even when there are no changes made to the file's contents. Important to consider, in case processes get triggered by such changes.

4. Conclusion

This was a quick introduction to saving and quitting in Vim. Certainly, the built-in help will give more information if we run the :help save or :help quit commands.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.