Skip to content

Linux Foundations / Find your way around Linux ยท Step 54 of 63

Lesson: Vim Saving and ExitingSwitch
โ† Linux Foundations

Shell and files

Vim Saving and Exiting

Write your work, quit Vim cleanly and understand its common warnings.

"How do I get out of Vim?" is a classic question. The answer is short: press Esc to reach Normal mode, type a command beginning with :, and press Enter.

The essential commands

  • :w writes (saves) the file and stays in Vim.
  • :q quits, if there are no unsaved changes.
  • :wq writes, then quits.
  • :q! quits and throws away unsaved changes.

If you try :q with unsaved work, Vim stops you:

text
E37: No write since last change (add ! to override)

The ! means "I mean it". Check that you really want to lose the changes before using it.

Shortcuts

  • :x writes only if the buffer was changed, then quits.
  • ZZ in Normal mode does the same as :x.
  • ZQ in Normal mode quits without saving.

The difference from :wq is small but real: :wq writes even when nothing changed, which updates the file's modification time.

Saving under another name

vim
:w backup.conf

This writes a copy to backup.conf, but you keep editing the original name. To switch to the new name, use :saveas backup.conf. If you started vim with no filename, plain :w fails with E32: No file name, so supply one.

To drop your changes and reload the file from disk without leaving, use :e!.

Read-only and permission problems

If you see E45: 'readonly' option is set (add ! to override), Vim is protecting the file. :w! overrides the option, but it cannot give you permissions you do not have in a directory or file system.

A common case is editing a system file without root rights. The cleanest fix is to quit and reopen it with:

bash
sudoedit /etc/hosts

If you have typed a lot already, save to a temporary location with :w ~/hosts.new, then copy it into place with sudo.

Several files

With more than one file or window open, :wa writes all changed buffers and :qa quits everything. :wqa does both.

Swap files

While you edit, Vim usually keeps a swap file such as .notes.txt.swp. If you later see an E325: ATTENTION message, either the file is open elsewhere or an earlier session ended badly. Read the choices on screen. If another Vim is still editing it, quit. If not, you can recover, compare the result, and then delete the old swap file.

Try it

  1. Run vim save.txt, press i, type a line, press Esc.
  2. Type :q and read the warning.
  3. Save with :w, then run :w copy.txt.
  4. Add another line, then leave with :q!.
  5. Run cat save.txt copy.txt. The second line you added is in neither.

Check your understanding

Vim Saving and Exiting

All 5 sections ยท no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.