Exiting the vi editor in Linux can be confusing for new users due to its unique modes and commands. Understanding how to properly exit ensures that you save your work or discard changes as needed.
vi Modes
The vi editor operates in two primary modes:
- Command Mode: Used for navigating and executing commands.
- Insert Mode: Used for inserting and editing text.
When vi starts, it is in Command Mode. To enter Insert Mode, press i. To return to Command Mode from Insert Mode, press Esc.\
Saving Changes and Exiting vi
- Press
Escto switch to Command Mode. - Type
:wqand pressEnter.
This command saves the current changes and exits the editor.
Exiting vi Without Saving Changes
- Press
Escto ensure you are in Command Mode. - Type
:q!and pressEnter.
This command quits vi without saving any changes made during the session.
Alternative Command for Saving and Exiting
- Ensure you are in Command Mode by pressing
Esc. - Type
:xand pressEnter.
The :x command saves changes only if they have been made and then exits vi.
Quitting vi Using Shortcut Keys
- Press
Escto enter Command Mode. - Press
Shift+Ztwice (ZZ).
Pressing ZZ saves any changes and exits the editor immediately.
Exiting When Esc Key Does Not Work
If the Esc key is unresponsive, try the following alternatives to switch to Command Mode:
- Press
Ctrl+[. - Press
Ctrl+C.
Once in Command Mode, use the appropriate command to exit vi.
Troubleshooting Common Issues
If you receive a warning when attempting to quit, such as:
E37: No write since last change (add ! to override)
This means there are unsaved changes. To quit without saving, use :q!. To save changes and quit, use :wq or ZZ.
Understanding how to properly exit vi ensures smooth navigation and prevents the loss of your work.