Closing a file in vi
When first working with vi, you will get at the point where you want to close it. But how do you do this?! It depends on whether you just want to close vi or whether you want to save or discard your changes when closing vi. To close vi you have to be in command mode (press ESC
to get there). You can learn more about the modes in vi here.
Closing vi without saving
If you have made changes to a file but want to exit vi without saving them, you can use the following command:
:q!
This command will immediately exit vi and discard any changes you made to the file.
Closing and saving your changes
To save your changes and exit vi, you can use the following commands:
:wq
:x
ZZ
Closing multiple files
If you have multiple files open and want to close all of them without saving, use the following command:
:qa!
If you have multiple files open in vi and want to save and close all of them, you can use the following command:
:qa
Recap
In this article we learned that vi offers several ways for closing a file, depending on whether you want to save changes or not and whether you have multiple files open or not. Remember, that you need to be in command mode to execute these commands. Here is an overview of the different commands:
Command | Result |
---|---|
:w | Save file |
:wq or :x or ZZ | Save file and close file |
:q! | Close vi without saving |
:qa! | Close multiple files without saving |
:qa | Save and close multiple files |
Watch it on YouTube
You can watch me explaining the different modi in vi and vim in this video: