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

  1. Press Esc to switch to Command Mode.
  2. Type :wq and press Enter.

This command saves the current changes and exits the editor.


Exiting vi Without Saving Changes

  1. Press Esc to ensure you are in Command Mode.
  2. Type :q! and press Enter.

This command quits vi without saving any changes made during the session.


Alternative Command for Saving and Exiting

  1. Ensure you are in Command Mode by pressing Esc.
  2. Type :x and press Enter.

The :x command saves changes only if they have been made and then exits vi.


Quitting vi Using Shortcut Keys

  1. Press Esc to enter Command Mode.
  2. Press Shift + Z twice (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.