How do I exit the Vim editor?
I'm stuck and cannot escape. It says:
"type :quit<Enter> to quit VIM"
But when I type that it simply appears in the object body.
Solution 1:
Hit the Esc key to enter "Normal mode". Then you can type :
to enter "Command-line mode". A colon (:
) will appear at the bottom of the screen and you can type in one of the following commands. To execute a command, press the Enter key.
-
:q
to quit (short for:quit
) -
:q!
to quit without saving (short for:quit!
) -
:wq
to write and quit -
:wq!
to write and quit even if file has only read permission (if file does not have write permission: force write) -
:x
to write and quit (similar to:wq
, but only write if there are changes) -
:exit
to write and exit (same as:x
) -
:qa
to quit all (short for:quitall
) -
:cq
to quit without saving and make Vim return non-zero error (i.e. exit with error)
You can also exit Vim directly from "Normal mode" by typing ZZ
to save and quit (same as :x
) or ZQ
to just quit (same as :q!
). (Note that case is important here. ZZ
and zz
do not mean the same thing.)
Vim has extensive help - that you can access with the :help
command - where you can find answers to all your questions and a tutorial for beginners.
Solution 2:
Pictures are worth a thousand Unix commands and options:
I draw this to my students each semester and they seem to grasp vi afterwards.
Vi is a finite state machine with only three states.
Upon starting, vi goes into COMMAND mode, where you can type short, few character commands, blindly. You know what you are doing; this isn't for amateurs.
When you want to actually edit text, you should go to INSERT mode with some one-character command:
- i: go to INSERT in the place of the cursor
- I: go to INSERT mode at the beginning of the line
- a: append after the cursor
- A: append at the end of line
- o: open a new line below the current line
- O: open a new line in the place of the current line
Now, answering the question: exiting.
You can exit vi from EX mode:
- q: if you haven't made any modifications, or saved them beforehand
- q!: ignores any modifications and quit
- wq: save and quit
- x: this is equal to wq
w
and x
accept a file name parameter. If you started vi with a filename, you need not give it here again.
At last, the most important: how can you reach EX mode?
EX mode is for long commands that you can see typing at the bottom line of the screen. From COMMAND mode, you push colon, :
, and a colon will appear at the bottom line, where you can type the above commands.
From INSERT mode, you need to push ESC, i.e. the Escape button, going to COMMAND mode, and then: to go to EX mode.
If you are unsure, push ESC and that will bring you to command mode.
The robust method is ESC-:-x-Enter which saves your file and quits.