如何阻止.swp文件生成?解决无法删除及暂存该文件的问题
Alright, let’s tackle your .swp file questions head-on—these are super common when working with Vim, so I’ll cover the "why" first, then fix both your issues.
.swap files (shortened to .swp) are Vim’s built-in safety net. When you open a file to edit, Vim creates this temporary file to save your unsaved changes in case something goes wrong—like your terminal crashing, SSH connection dropping, or you accidentally closing Vim without saving. Normally, when you exit Vim properly (with :wq or :q), it deletes the .swp file automatically. But if Vim exits unexpectedly, the .swp file sticks around.
If you’re stuck unable to remove these files or stage them in Git, here’s what’s going on and how to fix it:
- Vim might still be running in the background: Sometimes Vim can hang (especially if you disconnected from a remote session without exiting properly). Check for active Vim processes with:
Look for the process linked to your file, then kill it withps aux | grep vimkill <PID>(replace<PID>with the number from the output). Once the process is gone, you should be able to delete the .swp file withrm .filename.swp. - Permission issues: If you edited the file with sudo, the .swp file might be owned by root. Use
sudo rm .filename.swpto delete it in that case. - Want to recover unsaved changes?: If you open the original file in Vim, it’ll detect the .swp file and give you options. Press
Rto recover your changes, then save and exit normally—Vim will automatically delete the .swp file afterward. - Staging in Git? Don’t bother: .swp files are temporary, so you should add them to your
.gitignoreinstead. Just open.gitignoreand add a line:
Commit the .gitignore file, and Git will ignore all .swp files going forward.*.swp
Before we dive in, a quick heads-up: Disabling swap files means you lose Vim’s crash recovery feature. If you’re okay with that, here are your options:
- Temporary disable for a single edit: Start Vim with the
-nflag (short for "no swap file"):vim -n yourfile.txt - Permanent disable for all Vim sessions: Edit your Vim config file (usually
~/.vimrc; if it doesn’t exist, create it). Add this line:
Save the file, and the next time you open Vim, it won’t create any .swp files.set noswapfile - Middle ground: Move .swp files to a single directory: If you want to keep recovery but don’t want .swp files cluttering your project folders, set a dedicated swap directory in
.vimrc:
The double slash at the end tells Vim to use unique filenames for swap files, so you won’t get conflicts across projects. Just create theset directory=$HOME/.vim/swapfiles//~/.vim/swapfilesdirectory first withmkdir -p ~/.vim/swapfiles.
内容的提问来源于stack exchange,提问作者ark

