Exiting Vim can be confusing for new users because Vim operates in modes (e.g., Normal mode, Insert mode), and quitting requires specific commands. Below is a detailed guide with examples to exit Vim gracefully.
Step-by-Step Guide to Exit Vim
1. Ensure You’re in Normal Mode
Vim commands only work in Normal mode (not Insert mode).
- If you’re in Insert mode (where you can type text), press
Escto return to Normal mode. - Check the bottom-left corner of the screen: if you see
-- INSERT --, you’re in Insert mode.
2. Basic Exit Commands
Once in Normal mode, use one of these commands:
| Command | Action |
|---|---|
:q | Quit Vim (fails if unsaved changes exist). |
:q! | Force quit without saving changes (discards edits). |
:wq | Save changes and quit (write + quit). |
:wq! | Force save and quit (useful for read-only files if you have sudo). |
:x | Save (if changes exist) and quit (similar to :wq). |
ZZ (Shift + zz) | Save and quit (shortcut for :wq). |
:qa | Quit all open windows/tabs (if using splits or multiple files). |
Examples
Example 1: Quit Without Saving Changes
- Press
Escto ensure you’re in Normal mode. - Type
:q!and pressEnter.
- This exits Vim and discards all unsaved changes.
Example 2: Save and Quit
- Press
Esc. - Type
:wqand pressEnter.
- Saves changes to the file and exits.
Example 3: Save and Quit with a Filename
If you forgot to name the file when opening Vim:
- Press
Esc. - Type
:wq filename.txtand pressEnter.
- Saves the file as
filename.txtand exits.
Example 4: Quit Multiple Windows/Tabs
If you have split screens or tabs:
- Press
Esc. - Type
:qa!and pressEnter.
- Closes all open files/windows without saving.
Common Mistakes & Fixes
- “E37: No write since last change”
- You modified the file but didn’t save. Use
:q!to discard changes or:wqto save.
- “E212: Can’t open file for writing”
- You don’t have write permissions. Save with
sudo:bash :w !sudo tee % # Force-save with sudo :q! # Then quit
- Stuck in Visual/Command Line Mode
- Press
Escrepeatedly to return to Normal mode.
Last Resort: Force-Kill Vim
If you’re truly stuck:
- Open a new terminal window.
- Find the Vim process ID:
ps aux | grep vim
- Kill the process:
kill -9 <process_id>
- Warning: This discards all unsaved changes.
Summary Table
| Scenario | Command |
|---|---|
| Quit without changes | :q |
| Discard changes and quit | :q! |
| Save and quit | :wq or ZZ |
| Save as root (permission fix) | :w !sudo tee % |
| Quit all windows/tabs | :qa! |
Pro Tips
- Memorize
Esc→:q!as the universal “get me out of Vim” command. - Use
:help quitin Vim to open the official documentation. - Practice in a safe environment (e.g., open a test file with
vim test.txt).
With these commands, you’ll never be trapped in Vim again!