Vim how to save and exit

Vim how to save and exit

Как выйти из Vim

Как выйти из Vim? Как закрыть Vim? Как сохранить и выйти Vim? Подобные вопросы задают множество новичков, которые только начинают пользоваться редактором Vim. Это один из лучших редакторов, работающих в терминале. Он известен благодаря своей огромной функциональности.

Но новым пользователям очень неудобно пользоваться редактором из-за непривычных сочетаний клавиш. В этой статье мы рассмотрим несколько способов как выйти из Vim. А также несколько интересных фактов о выходе из Vim.

Как выйти из Vim

Если вы уже интересовались статьями о Vim, то, наверное, знаете, что существует несколько способов закрыть Vim. Вот самые популярные из них:

Нажмите клавишу Esc, это важно, потому что вам необходимо выйти из режима вставки, прежде чем вводить команды выхода. Далее можете вести одну из следующих команд:

После ввода любой из команд нужно нажать Enter. Обратите внимание, что при нажатии Esc и ввода символа «:» курсор ввода переместится вниз окна.

Vim how to save and exit. Смотреть фото Vim how to save and exit. Смотреть картинку Vim how to save and exit. Картинка про Vim how to save and exit. Фото Vim how to save and exit

Другие способы выйти из Vim

Как правило, вам будет достаточно помнить три приведенные выше команды чтобы правильно выйти из Vim в большинстве ситуаций. Но существует еще несколько способов:

Факты о выходе из Vim

Если вы чувствуете себя неловко, потому что не знаете как выйти из Vim, не расстраивайтесь. Вы не одиноки, согласно статистике StackOverflov более миллиона разработчиков со всего мира не знают как выйти из редактора vim.

В самом деле, выход из Vim стал темой для анекдотов и частью культуры. Например, один из популярных твитов, который акцентирует внимание на сложности выхода из Vim:

Vim how to save and exit. Смотреть фото Vim how to save and exit. Смотреть картинку Vim how to save and exit. Картинка про Vim how to save and exit. Фото Vim how to save and exit

Это немного удивительно, потому что если вы запустите Vim без параметров, то увидите информацию о том, как его закрыть прямо на заставке:

Vim how to save and exit. Смотреть фото Vim how to save and exit. Смотреть картинку Vim how to save and exit. Картинка про Vim how to save and exit. Фото Vim how to save and exit

Выводы

How to Exit a File in Vi / Vim Editor in Linux

In this article, we will learn how to exit Vi/Vim (after referred to as Vim) text editor using simple commands. In a previous article, we explained a simple tip on how to save a file in Vi or Vim after making changes to a file.

Before we move any further, if you are new to Vim, then we recommend reading through these 10 reasons why you should stick to using Vi/Vim text editor in Linux.

To open or create a new file using Vi/Vim, simply type the commands below, then press i to switch to insert mode (insert text):

Vim how to save and exit. Смотреть фото Vim how to save and exit. Смотреть картинку Vim how to save and exit. Картинка про Vim how to save and exit. Фото Vim how to save and exit Press ‘i’ to Insert Mode in Vim Editor

After making changes to a file, press [Esc] to shift to the command mode and press :w and hit [Enter] to save a file.

Vim how to save and exit. Смотреть фото Vim how to save and exit. Смотреть картинку Vim how to save and exit. Картинка про Vim how to save and exit. Фото Vim how to save and exit Save File in Vim

Vim how to save and exit. Смотреть фото Vim how to save and exit. Смотреть картинку Vim how to save and exit. Картинка про Vim how to save and exit. Фото Vim how to save and exit Exit File in Vi Editor

To save a file and exit Vi/Vim simultaneously, use the :wq command and hit [Enter] or 😡 command.

Vim how to save and exit. Смотреть фото Vim how to save and exit. Смотреть картинку Vim how to save and exit. Картинка про Vim how to save and exit. Фото Vim how to save and exit Save and Exit File in Vi

If you make changes to a file but try to quite Vi/Vim using ESC and q key, you’ll receive an error as shown in the scrrenshot below.

Vim how to save and exit. Смотреть фото Vim how to save and exit. Смотреть картинку Vim how to save and exit. Картинка про Vim how to save and exit. Фото Vim how to save and exit Vi Error Quitting File

Vim how to save and exit. Смотреть фото Vim how to save and exit. Смотреть картинку Vim how to save and exit. Картинка про Vim how to save and exit. Фото Vim how to save and exit Force Quit Vi File in Linux

Additionally, you can use shortcut methods. Press the [Esc] key and type Shift + Z Z to save and exit or type Shift+ Z Q to exit without saving the changes made to the file.

Having learned the above commands, you can now proceed to learn advanced Vim commands from the links provided below:

In this article, we learned how to exit Vim text editor using simple commands. Do you have any questions to ask or any thoughts to share? Please, use the feedback form below.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Vim how to save and exit. Смотреть фото Vim how to save and exit. Смотреть картинку Vim how to save and exit. Картинка про Vim how to save and exit. Фото Vim how to save and exit

We are thankful for your never ending support.

VIM Exit and Save, for Beginners

Syntax to Exit and Save from VIM Editor

Press esc key to ensure you are in command mode. Then press the colon key to enter command line mode. Command line mode will have a colon at the bottom left of the screen where you can enter command lines. Then press ‘wq’ and ‘enter’ to indicate exit and save. ‘w’ is short for write indicating save the file contents to disk. ‘q’ is short for quit which indicates exit vim editor.

The screenshot below is of entering the ‘wq’ command in command line mode to instruct vim to exit the program after saving the contents, aka write and quit.

Vim how to save and exit. Смотреть фото Vim how to save and exit. Смотреть картинку Vim how to save and exit. Картинка про Vim how to save and exit. Фото Vim how to save and exit

Understanding VIM Modes and How to use Them

Vim’s primary modes of operation are Insert Mode, Command Mode, Command Line Mode and Visual Mode. The editor will be in one of these modes at any time, and interacting with the vim editor using keystrokes will take different actions depending on which mode the editor is currently in. If you try to enter ‘wq’ to save and exit, when in insert mode it will not in fact save the contents you are working on nor exit the vim editor. So therefore you need to be aware when using vim which mode you are in.

Insert Mode: in this mode you can actually type content into a file. You are doing editing and not instructing Vim the editor what to do other than what text to enter into a file contents. You can enter Insert Mode from the Command Mode by hitting the ‘i’ key which stands for insert. You can also hit the ‘a’ key which will also enter the insert mode, but after moving the cursor after the current position, which is why ‘a’ in this case stands for append.

Command Mode: this is the mode where keystrokes are used to instruct vim what to do and how to function but not for entering new text or editing text in a file. To enter Command Mode hit the ‘esc’ key on the keyboard.

Command Line Mode: a little mini command line prompt appears at the bottom left of the screen and allows you to enter commands such as we have shown in this tutorial, you can use ‘w’ which stands for writing a file and you can use ‘q’ which stands for quitting the editor. These can be combined into a single instruction and you will exit the editor and save the file.

Visual Mode: visual mode allows you to highlight text and then use that selected text in copy and paste or other common operations on selected text. All of this can be done from the keyboard without a mouse unlike GUI based editors such as Notepad or Visual Studio.

How to Save Your Contents but not Exit the Editor

If you want to save your work in the file you are editing but not exit the vim editor just use the ‘w’ command to write the file and omit the ‘q’ command as shown below.

Vim how to save and exit. Смотреть фото Vim how to save and exit. Смотреть картинку Vim how to save and exit. Картинка про Vim how to save and exit. Фото Vim how to save and exit

How to Exit the Editor But Not Issue a Save

If you want to exit the editor only, and not issue a save command, then just issue the ‘q’ command in the command line mode as shown below. This command assumes you have not made any changes so far to the content or else you will get an error as shown in the second screenshot below.

Vim how to save and exit. Смотреть фото Vim how to save and exit. Смотреть картинку Vim how to save and exit. Картинка про Vim how to save and exit. Фото Vim how to save and exit

Vim how to save and exit. Смотреть фото Vim how to save and exit. Смотреть картинку Vim how to save and exit. Картинка про Vim how to save and exit. Фото Vim how to save and exit

Error above because exit command was issued without a save file command.

How to Exit the Editor But and Not Save Changes

If you have made changes, but you DO NOT want to save these changes to disk and want to revert to the previous content at the time of the last save issue the ‘q’ command with the ‘!’ command at the command line mode as shown below.

Vim how to save and exit. Смотреть фото Vim how to save and exit. Смотреть картинку Vim how to save and exit. Картинка про Vim how to save and exit. Фото Vim how to save and exit

Conclusion

All of the information above may seem like too much complexity just to exit the editor and save the contents of the file you are working on, but there are reasons for it and everything is logical. The vim editor can be operated almost entirely from the keyboard without use of the mouse which is ergonomically and speed wise usually more efficient for programmers and experience IT professionals. Therefore all of the instructions must be specified with different key combinations and not the use of a graphical mouse pointer. In order to accommodate rapid programming and usage of VIM the different modes of operation were introduced so the same keys can have different actions depending on the current mode. So when you want to do a quick simple command to exit the editor while at the same time saving the contents of the file you are doing, it’s just a few keystrokes on the editor and not browsing through menus with a clumsy mouse. Learn the tricks of VIM and you will be on the path to being an elite coder or systems administrator.

More VIM Education

About the author

Vim how to save and exit. Смотреть фото Vim how to save and exit. Смотреть картинку Vim how to save and exit. Картинка про Vim how to save and exit. Фото Vim how to save and exit

Linux Wolfman

Linux Wolfman is interested in Operating Systems, File Systems, Databases and Analytics and always watching for new technologies and trends. Reach me by tweeting to @linuxhint and ask for the Wolfman.

How do I exit Vim?

I am stuck and cannot escape. It says:

But when I type that it simply appears in the object body.

Vim how to save and exit. Смотреть фото Vim how to save and exit. Смотреть картинку Vim how to save and exit. Картинка про Vim how to save and exit. Фото Vim how to save and exit

13 Answers 13

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

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.

You can also exit Vim directly from «Normal mode» by typing ZZ to save and quit (same as 😡 ) or ZQ to just quit (same as :q! ). (Note that case is important here. ZZ and zz do not mean the same thing.)

Pictures are worth a thousand Unix commands and options:

Vim how to save and exit. Смотреть фото Vim how to save and exit. Смотреть картинку Vim how to save and exit. Картинка про Vim how to save and exit. Фото Vim how to save and exit

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:

Now, answering the question: exiting.

You can exit vi from EX mode:

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?

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.

Vim how to save and exit. Смотреть фото Vim how to save and exit. Смотреть картинку Vim how to save and exit. Картинка про Vim how to save and exit. Фото Vim how to save and exit

Before you enter a command, hit the Esc key. After you enter it, hit the Return to confirm.

Commands marked with ‘*’ are Vim-only (not implemented in Vi).

Safe-quit (fails if there are unsaved changes):

Prompt-quit (prompts if there are unsaved changes)

Write (save) changes and quit:

Discard changes and quit:

Press Return to confirm the command.

This answer doesn’t reference all Vim write and quit commands and arguments. Indeed, they are referenced in the Vim documentation.

Vim has extensive built-in help, type Esc :help Return to open it.

This answer was inspired by the other one, originally authored by @dirvine and edited by other SO users. I’ve included more information from Vim reference, SO comments and some other sources. Differences for Vi and Vim are reflected too.

🐧 Как сохранить файл в Vi / Vim и выйти

Vim how to save and exit. Смотреть фото Vim how to save and exit. Смотреть картинку Vim how to save and exit. Картинка про Vim how to save and exit. Фото Vim how to save and exit

Vi – это текстовый редактор командной строки для систем на базе Unix / Linux.

Vim (Vi IMproved) – многофункциональный преемник текстового редактора Vi с множеством улучшений и удобств для пользователя.

Vim how to save and exit. Смотреть фото Vim how to save and exit. Смотреть картинку Vim how to save and exit. Картинка про Vim how to save and exit. Фото Vim how to save and exit

Как сохранить изменения в Vim

В этой части вы узнаете, как сохранить изменения в Vim, не выходя из редактора.

Вышеупомянутый процесс сохранит изменения в текущем редакторе vi / vim.

Ваш файл останется открытым в редакторе для дальнейших изменений.

Как сохранить файл и выйти из Vim

В этой части вы узнаете, как сохранить изменения в Vim, и выйти из редактора.

Другие команды сохранения и выхода в Vi / Vim

В приведенных выше методах вы узнали о сохранении файла и выходе из редактора vim.

Есть и другие методы.

Первые два шага останутся такими же, как указано выше:

Теперь используйте одну из следующих команд в соответствии с вашими требованиями.

КОМАНДазначение
:w
:wqЗаписать изменения в файл и закрыть редактор
:wq!Принудительно записать изменения в файл и выйти, даже если у файла есть только разрешение на чтение
:q

Заключение

Это руководство поможет вам понять, как сохранить файл и выйти из него в редакторе vi / vim.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *