Русские Блоги
Временные скрытые файлы с расширениями swp и swo под CentOS Linux
Скрытые файлы с расширениями swp и swo под CentOS Linux
версия системы:
CentOS Linux 6.8
Сцены:
При сегодняшней проверке системы oracle я обнаружил, что размер каталога / home превышает 80%. Поскольку обычно не разрешается превышать это значение, давайте посмотрим, какие журналы или файлы можно удалить, чтобы освободить место. Приходить.
Случайно обнаружил, что в папке журнала есть 7 ГБ данных, но вы можете использовать ls, чтобы увидеть только один файл, но его размер составляет всего 3 ГБ, попробуйте использовать ls -a Проверьте, есть ли скрытые файлы. Конечно, есть два скрытых файла с именем файла:
.listener.log.swp
.listener.log.swo
Роль swp временно скрывает файлы:
Временные файлы могут быть удалены. Используйте rm для удаления.
Как создать временные скрытые файлы в swp:
После первого открытия файла с помощью vi будет создан скрытый файл с суффиксом swp (сейчас вы увидите его при использовании другого порта сеанса);
Если второе окно одновременно открывает тот же файл, в это время будет создан скрытый файл со вторым временным файлом swo в качестве суффикса;
По аналогии третий временный скрытый файл — это swn;
То есть правило имени файла: сначала swp, за которым следуют буквы против часовой стрелки, а именно: swp, swo, swn, swm .
Сначала мне было немного любопытно, сколько там временных скрытых файлов?
Затем я проверил его. Сначала я подумал, что он не появится снова после появления всех букв, но это не так.
После появления swq файл с суффиксом swp появится в следующий раз (конечно, этот файл обычно не открывается в таком количестве окон).
Если при открытии файла произошла авария, например, закрытие порта сеанса или выключение компьютера, временно скрытый файл будет сохранен, как в версии 6.8.
Но в 7.5 В среде версий указанная выше операция не сохранит временный скрытый файл swp;
Однако в среде версии 7 после открытия одного и того же файла в более чем 20 окнах было сгенерировано более 20 временных скрытых файлов. В случае аварии некоторые файлы все равно будут сохранены.
[Solved] Found a swap file by the name .XXX.swp
Are you getting «Found a swap file by the name» for some file with .swp extension? Are you trying to open a file using some editor such as vim or vi and getting this message? Do you want to get rid of this message? The solution is quite easy, just delete the reported .swp file but hey It is important that you fix this properly or you may loose unsaved data.
In this tutorial I will share the steps to fix this WARNING message in a proper way, there can be various scenarios under which you get this message so please read the text properly before taking any ACTION
What is .swp file? Why do I need this file ?
- Before we go into the solution part, do you know what is this .swp file and why is it there? and if you really need this file?
- Please NOTE even though the extension uses .swp , these files are not related SWAP memory so do not get confuse with them
- A .swp file is created as soon as we open a file using Vim/Vi editor
- On Unix and Linux, a ‘ . ‘ is prepended to swap file names in the same directory as the edited file.
- This avoids that the swap file shows up in a directory listing as Unix and Linux will consider it as hidden file.
- Vim stores the things you changed in a swap file.
- Using the original file you started from plus the swap file you can mostly recover your work.
- You can see the name of the current swap file using :sw[apname]
- The name of the swap file is normally the same as the file you are editing, with the extension «. swp «
- If this file already exists (e.g., when you are recovering from a crash) a warning is given and another extension is used, » .swo «, » .swn «, etc.
- An existing .swp file will never be overwritten.
- The swap file is deleted as soon as Vim stops editing the file.
You can learn more about this file using
Is it safe to delete .swp file
- The answer is not that straight forward
- It is possible that the same file is being modified by different users at the same time using any editor.
- So assuming user root is modifying the content of /tmp/file in terminal 1 and another user logs in as root from different terminal and attempts to access the same file for editing
- In such case you will get
- So we know that someone is already accessing this file at PID 1453
- So in such case it is recommended to quit the editor without making any changes.
- As if you choose to Continue with Edit then there will be two different swap file created with different extensions, as you can see here:
- This can cause problem because there will be two different version of same file
- So if you get below message along with » Found a swap file by the name «
- Then you should choose to Quit or Abort so that the changes from first user are intact and do not delete the .swp file. Although you can open the file in Read Only mode to just view the changes
How to fix “Found a swap file by the name”?
The fix is quite simple to overcome this warning i.e. just go ahead and delete the reported .swp file using rm -f /path/.file.swp
But with this you loose any chance of file recovery. So it is important that you first recover the content from .swp file before you delete it.
A Sample snippet of this WARNING
Recover from swp file into a different file
- It is possible that your last Vim/Vi session crashed for some reason while you were editing some file and your latest changes were not saved
- In my case I have /tmp/file which crashed and I could not save the latest content
- Now when I try to open /tmp/file using vim editor, I get this warning » Found a swap file by the name «/tmp/.file.swp» «
- Now I have an option to RECOVER the content but I am not sure what contents would be restored?
It is good practice to write the recovered file elsewhere. So I will create a new file file_recover , you can use any name as that doesn’t matter
Next open this file using vi/vim editor
Press Esc and enter :rec <path/of/file> to perform the recovery in this new file. For our example :rec /tmp/file
![[Solved] Found a swap file by the name](https://www.golinuxcloud.com/wp-content/uploads/2020/05/recover_in_different_file-1.jpg)
Initiate File Recovery
This command will recover the content of /tmp/file using /tmp/.file.swp into your current file i.e. /tmp/file_recover . Check the status of the Recovery. As it is also possible that if your .swp file is corrupted then Recovery may Fail
![[Solved] Found a swap file by the name](https://www.golinuxcloud.com/wp-content/uploads/2020/05/recovery_completed.jpg)
Recovery Completed
Next to compare the difference between the recovered and original content, press Esc followed by :DiffOrig and hit Enter
![[Solved] Found a swap file by the name](https://www.golinuxcloud.com/wp-content/uploads/2020/05/compare.jpg)
Initiate DiffOrig for Comparison
This will divide your terminal into two window with the difference of content between original and recovered file. Here you can check and decide if you wish to continue with recovery.
![[Solved] Found a swap file by the name](https://www.golinuxcloud.com/wp-content/uploads/2020/05/recovered-content.jpg)
Compare the content after recovery If you choose to continue with Recovery then you can exit from both the files without saving. Press Esc followed by :q to exit without saving
Now open your original file using vi or vim editor which will again show you the warning , you will also see below message at the bottom of the terminal
![[Solved] Found a swap file by the name](https://www.golinuxcloud.com/wp-content/uploads/2020/05/recover.jpg)
Fix Found a swap file by the name Since we know the Recovery works, press «R» to initiate the recovery
![[Solved] Found a swap file by the name](https://www.golinuxcloud.com/wp-content/uploads/2020/05/recovery_completed_1.jpg)
Recovery Completed So the recovery was successful. Press Enter to continue with editing of the document.
Once you are sure the recovery is ok delete the swap file . Otherwise, you will continue to get warning messages that the «.swp» file already exists
Recover from swp file into same file
If you know the contents which has changed and you don’t need to do any type of comparison then you can directly go ahead and recover the content from .swp file using vim -r <file>
For example, here I will directly edit the file using vim with -r to open the file and also recover the content from last saved swp buffer
The snippet from output from this command
![[Solved] Found a swap file by the name](https://www.golinuxcloud.com/wp-content/uploads/2020/05/recovery_completed_2.jpg)
Use vim -r to recover This shows that the Recovery was completed. Hit Enter to continue editing the document.
Once you are done save and exit the file and go ahead and delete the swp file to avoid further warning
Delete swp file without recovery
If you do not wish to recover the contents from your last saved state in the swap file. You can just go ahead and delete the .swp file to avoid any further warning.
IMPORTANT NOTE: Once this .swp file is deleted there is no way to know the changes which will get lost in your original file. So I hope you know what you are doing
How to avoid using swap file?
- So you don’t want to use swap file? This is possible but not recommended
- You can start the editing of a file using vim -n where -n will make sure there are no swap files created when editing the respective file
- In such case if vim crashes then there is no possible way to recover your unsaved data from this file
In this example from terminal 1 I will open /tmp/file for editing
From a different file, if I check for .swp files for this file
As expected no .swp files were created
Conclusion
In this tutorial we learned all about swp files, why it is important to use these swp files and how to fix » Found a swap file by the name «. It is very much possible that due to some unexpected event your existing vim/vi session crashed which would normally mean that all your saved changes are lost. But NO.
Vim/Vi editor keeps a copy of your changes in these .swp files. The content in these swp files are updated after typing 200 characters or when you have not typed anything for four seconds.This only happens if the buffer was changed, not when you only moved around. The reason why it is not kept up to date all the time is that this would slow down normal work too much.
It is recommended in most scenarios to first compare the buffer difference between original and recovered file content before you go ahead and delete the .swp file
Lastly I hope the steps from the article to to overcome Found a swap file by the name warning on Linux was helpful. So, let me know your suggestions and feedback using the comment section.
References
I have used below external references for this tutorial guide
Vim Swap File and Recovery
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
What causes swap files to be created?
As part of the program I wrote, I constantly read and write data from files. I noticed that as part of doing so, I am inadvertently creating swap .swp files.
What do you think is going on? What would cause swap files to appear if you had to reproduce the problem?
4 Answers 4
The .swp file is not a swap file in the OS sense. It is a state file. It keeps your changes since the last save (except the last 200 characters), buffers that you have saved, unsaved macros and the undo structure.
You can read more in VIM’s help: vim +help\ swap-file . If there is a crash (power failure, OS crash, etc.), then you can recover your changes using this swap-file. After saving the changes from the swap file to the original file, you will need to exit vim and remove the swap file yourself.
Что использует swp?
Запустил htop, параметр swp — 5GB.
Скажите, пожалуйста, это в реальном времени он так забит или это за какое-то время?
Ну и как определить процесс, который его занимает?
В линуксе я не очень. Помогите, пожалуйста.
UPD:
Еще вопрос: почему у меня при наличии свободной памяти заполняется своп? Вот в том же htop я вижу Mem: 25GB/31GB, Swp: 4GB. То есть там и память еще есть.
Кроме того, у меня бОльшая часть памяти выделена для кэша mysql, и, как я понимаю, при нехватке памяти будет просто вычищаться кэш.