How to Exit Vim in Linux: Simple Commands Explained
To exit
vim in Linux, press Esc to enter normal mode, then type :q and press Enter to quit. If you have unsaved changes, use :wq to save and quit or :q! to quit without saving.Syntax
In vim, commands to exit start with a colon : which puts you in command mode. Here are the main commands:
:q- Quit if no changes were made.:wq- Write (save) changes and quit.:q!- Quit without saving changes.
Press Esc first to ensure you are in normal mode before typing these commands.
vim
:q :wq :q!
Example
This example shows how to exit vim after editing a file:
- Press
Escto enter normal mode. - Type
:wqand pressEnterto save changes and exit.
bash
vim example.txt # (make some changes) # Press Esc :wq # Vim exits and saves the file
Output
user@linux:~$ vim example.txt
# (vim opens the file)
# After editing and typing :wq
user@linux:~$
Common Pitfalls
Many beginners get stuck because they don't press Esc before typing commands or try to exit while still in insert mode. Also, trying :q when there are unsaved changes will show an error.
Wrong way: Typing :q without pressing Esc or with unsaved changes.
Right way: Press Esc first, then use :wq to save and quit or :q! to quit without saving.
vim
iHello world :q # Error: No write since last change (add ! to override) <Esc> :wq # Saves and exits
Output
"example.txt" 1L, 12C written
Quick Reference
| Command | Description |
|---|---|
| :q | Quit Vim (only if no changes) |
| :wq | Save changes and quit |
| :q! | Quit without saving changes |
| Esc | Switch to normal mode before commands |
Key Takeaways
Always press Esc to enter normal mode before exiting Vim.
Use :q to quit only if no changes were made.
Use :wq to save changes and exit safely.
Use :q! to force quit without saving changes.
Remember Vim commands start with a colon in command mode.