Vim Swap Corruption — The Hidden Danger of SSH Disconnects
E325 swap file warning after SSH disconnect? Recovering can write broken configs.
20+ years shipping production infrastructure and CI/CD at scale. Lessons pulled from things that broke in production.
- Vim is a modal text editor with three primary modes: Normal (commands), Insert (typing), and Command (save/quit).
- Normal mode is the default — every key is a command, not a character. Press 'i' to type.
- Navigation: h/j/k/l (left/down/up/right), w/b (word forward/back), gg/G (first/last line).
- Editing: dd (delete line), yy (copy line), p (paste), u (undo). All in Normal mode.
- Quitting: :wq (save+quit), :q! (quit discard). Enter Command mode with ':'.
- Production insight: Most vim panics happen because you're in the wrong mode. Escape always resets to Normal mode.
Imagine a Swiss Army knife where each tool only works when you flip a specific switch. That's vim — a text editor with distinct 'modes', where the same key does completely different things depending on which mode you're in. Most editors behave like a notepad: you open it and just start typing. Vim is more like a cockpit — incredibly powerful once you know the controls, but confusing until someone explains what each switch does. Once it clicks, you'll edit text faster than you ever thought possible.
Every DevOps engineer, Linux sysadmin, or backend developer will eventually find themselves staring at a vim prompt on a remote server — heart racing, fingers frozen — because it's the one editor that's guaranteed to be installed on virtually every Unix-based system on the planet. Whether you're editing a cron job at 2 AM or fixing a config file on a production server where no GUI exists, vim is the tool that's always there waiting for you.
The problem is that vim doesn't work like any editor you've used before. Press a key and instead of typing a letter, something completely unexpected happens. Try to close the window and nothing works. This isn't a bug — it's by design. Vim was built for speed and efficiency on keyboards that predate the mouse, and its modal design is the secret to that power. The confusion beginners feel is almost always because nobody explained the ONE core concept: vim has modes, and everything depends on which mode you're currently in.
By the end of this article you'll know exactly how to open and close vim without panicking, navigate a file without touching the mouse, switch between modes confidently, make real edits to text files, and save your work. You'll go from 'how do I even quit this thing?' to genuinely understanding why experienced developers swear by vim for fast, precise editing.
What Vim Editor Basics Actually Covers
Vim is a modal text editor where the core mechanic is that keystrokes have different meanings depending on the current mode — normal, insert, visual, or command. This design eliminates the need for mouse or arrow-key churn, letting you edit at the speed of thought once the modes become reflexive. The modal system is not a gimmick; it's a deliberate optimization for reducing hand movement and keystroke count, directly translating to faster editing over a session.
In practice, Vim's key properties are its composable commands (e.g., d2w = delete two words) and its buffer/swap file architecture. Every open file is backed by a .swp swap file that records unsaved changes. This swap file is the safety net against crashes, but it's also the source of corruption when an SSH session drops mid-write. The swap file is not a log — it's a snapshot, and an interrupted write can leave both the original file and the swap in an inconsistent state.
You use Vim basics — modes, motions, and swap awareness — every time you edit a config file on a remote server. In production, this matters because a dropped SSH connection during a :w can corrupt the swap file, leading to recovery prompts that confuse junior engineers and cause accidental data loss. Understanding the swap mechanism is not optional; it's the difference between recovering a config and rebuilding a server.
:w — the swap file was written partially, and the recovery prompt offered a corrupted version as the 'original'. The symptom was a swap file with a mismatched checksum that Vim presented as a recovery option, but the recovered file had truncated lines. Rule: never trust a swap file from an interrupted write; always diff against a backup or version control.:w) — swap files are not a safety net.Vim's Three Modes — The Core Concept Everything Else Builds On
Here's the single idea that unlocks vim: it has modes. Most editors have one mode — 'typing mode'. You open the editor, you type, your words appear. Vim has three primary modes, and each one turns your keyboard into a completely different tool.
Normal Mode is where vim starts. Your keyboard acts like a remote control — every key is a command, not a letter. Press 'd' and it doesn't type the letter d; it begins a delete operation. This feels wrong at first, but it's actually brilliant: most of your time editing is not typing new text, it's navigating, deleting, copying and moving existing text. Normal mode is optimised for that.
Insert Mode is what you're used to. Here, every key types a character exactly like a standard editor. You enter Insert mode by pressing 'i' from Normal mode, do your typing, then press Escape to return to Normal mode.
Command Mode (also called Ex mode) is for file-level operations: saving a file, quitting, search-and-replace across the whole document. You enter it by pressing ':' from Normal mode.
Think of it like a car: Normal mode is when you're steering and navigating, Insert mode is when you're actually loading cargo, and Command mode is the dashboard — save trip, quit navigation, check settings. You switch lanes, not everything at once.
Navigating a File in Vim — Moving Around Without a Mouse
Once you understand modes, navigation is your next superpower. In Normal mode, vim gives you precise, keyboard-driven movement that — once learned — is genuinely faster than reaching for a mouse.
The foundational movement keys are h, j, k, l — they map to left, down, up, right respectively. This sounds arbitrary, but it was intentional: these keys sit directly under your right hand's resting position on a QWERTY keyboard, so you never have to move your hand to navigate.
But letter-by-letter movement is slow. Here's where vim starts to feel magical. 'w' jumps forward one word at a time. 'b' jumps backward one word. '0' (zero) jumps to the absolute start of the current line. '$' jumps to the end of the current line. 'gg' teleports you to the very first line of the file. 'G' (capital G) teleports you to the very last line.
You can also combine numbers with movements. '5j' moves down 5 lines. '3w' jumps forward 3 words. This number-plus-command pattern is a core vim concept called a motion multiplier — it's what makes experienced vim users look like they're casting spells.
For searching, press '/' in Normal mode, type your search term, and press Enter. Vim highlights all matches and jumps to the first one. Press 'n' to jump to the next match, 'N' to go backward.
Editing Text in Vim — Deleting, Copying, Pasting and Undoing
This is where vim stops feeling like a weird editor and starts feeling like a superpower. All editing commands work in Normal mode, which means you never have to click-and-drag to select text or reach for a menu. Everything is a keyboard shortcut.
Deleting: The 'd' key is your delete tool. But 'd' alone does nothing — it waits for a motion. 'dw' deletes from the cursor to the end of the current word. 'd$' deletes from the cursor to the end of the line. 'dd' (press d twice) deletes the entire current line. '3dd' deletes 3 lines at once.
Copying (Yanking): Vim calls copying 'yanking'. The 'y' key works exactly like 'd' but copies instead of cuts. 'yy' yanks the entire current line. 'yw' yanks one word.
Pasting: Press 'p' (lowercase) to paste after the cursor. Press 'P' (uppercase) to paste before the cursor. After a 'dd' or 'yy', the content lives in vim's internal clipboard.
Undoing and Redoing: Press 'u' in Normal mode to undo the last action. Press 'Ctrl + r' to redo it. Vim has a deep undo history — keep pressing 'u' to step back through multiple changes.
Changing text in place: The 'c' key is like 'd' but drops you into Insert mode after deleting. 'cw' deletes the current word and immediately lets you type a replacement. It's the fastest way to replace a word.
Saving, Quitting and the Commands You'll Use Every Single Day
The most Googled vim question of all time is 'how do I exit vim'. It's even a running joke in developer culture. The reason it trips people up is that quitting is a Command mode operation, and most newcomers get stuck because they're in the wrong mode and don't know it.
Here's the complete map of save/quit commands. Enter Command mode first by pressing ':' in Normal mode, then type the command:
':w' — Write (save) the file but stay in vim. Use this habitually as you work. ':q' — Quit vim. Only works if you haven't made unsaved changes. ':wq' — Write and quit in one step. This is your main exit command. ':q!' — Quit WITHOUT saving. The '!' forces it, discarding all changes. Use when you want to abandon edits. ':w filename.txt' — Save as a new filename (like 'Save As').
Beyond saving, these Command mode tools will save you hours:
':%s/old_word/new_word/g' — Find and replace. The '%' means 'whole file', 's' means substitute, 'g' means all occurrences on each line. This is the sed command, but live inside your file.
':set number' — Show line numbers. Incredibly useful when debugging config files or referencing error line numbers from logs.
':syntax on' — Enable syntax highlighting if it isn't already active.
Visual Mode and Advanced Editing Techniques
Beyond basic editing, vim offers Visual mode for selecting text by character, line, or block. This is how you perform operations on a sub-section of text without typing coordinates.
Press 'v' in Normal mode to enter Visual mode character-wise. Move the cursor to expand the selection. Then press 'd' to delete, 'y' to yank, 'c' to change, or '>' to indent. Press 'V' for line-wise visual mode (selects whole lines). Press 'Ctrl+v' for block-wise visual mode — useful for editing columns of data, like adding a comment prefix to multiple lines.
Advanced actions: - '.': Repeat the last change. Incredibly powerful for repetitive edits. - '>>' and '<<': Indent/outdent the current line. - '==': Auto-indent the current line based on file type. - '~': Toggle case of the character under the cursor. - 'J': Join the current line with the line below. - 'Ctrl+a' and 'Ctrl+x': Increment/decrement the number under the cursor (e.g., change 'port 8080' to 'port 8081').
Working with multiple files: - ':e filename' — Open another file in the same vim session. - ':bnext' or ':bn' — Switch to the next buffer (open file). - ':ls' — List all open buffers. - ':bd' — Close the current buffer (file).
- d + w = delete word (verb + motion)
- c + $ = change to end of line
- y + t( = yank everything until next '(' (include? no)
- v + j + ~ = visual select down, then toggle case
- The '.' repeats the last verb-noun combo — instant macro
Installation and Getting Started — Because Vim Isn't Always There
You SSH into a production box to read a log file. You type vim. You get "command not found." That's a bad start to an incident. Vim ships with most Linux distributions, but not all — especially minimal containers or trimmed cloud images.
Fix it before you need it. On Debian/Ubuntu: sudo apt-get install vim -y. On RHEL/CentOS/Fedora: sudo yum install vim -y. On Arch: sudo pacman -S vim. After installation, confirm with vim --version.
You don't always need a file to start. Running vim alone opens a blank buffer. More useful: vim /var/log/syslog or vim config.yml. The file loads immediately. You're in Normal mode. Don't panic — you haven't broken anything. You just can't type yet. That's intentional. From here, every keystroke becomes a command, not a character. That's the power.
One more thing: your .vimrc file — stored at ~/.vimrc — controls behavior. No .vimrc means stock settings. Create one with set number to show line numbers. It's the first thing I add on every new machine. Do it now.
command not found error on a broken server adds minutes to MTTR.Search and Replace — Your Log Forensic Tool
You're triaging a failed deployment. The log file is 20,000 lines. Scrolling is not debugging. You need to find the error fast — and then replace a misconfigured IP across the entire config.
Search in Vim is instant. In Normal mode, type /<pattern> and press Enter. Vim jumps to the next match. Press n for next, N for previous. Case matters by default. To ignore case, run :set ignorecase before your search. To match whole words only: :set smartcase.
For replacing, you use the colon commands. The pattern is always :[range]s/old/new/[flags]. No range = current line only. % means entire file. The g flag applies to all matches on a line, not just the first. The c flag asks for confirmation before each replacement — use this when you're not 100% sure.
Examples: :s/foo/bar/ replaces first 'foo' on current line. :%s/foo/bar/g replaces every 'foo' in the file. :3,10s/foo/bar/gc replaces with confirmation on lines 3-10. Predictable. Repeatable. No mouse required.
\. to match a literal period. Always test your pattern with a search first — /pattern — before running :s. Saves you from replacing the wrong text across 500 lines.:%s/old/new/g for global search-replace. Add c flag to confirm changes. This pattern works on any file, any language, any server.Swap File Corruption After SSH Disconnect
- Always use :w frequently when editing production configs — every explicit save writes a clean checkpoint.
- The swap file is a snapshot of your in-progress edits — it can contain incomplete, broken content.
- If you get disconnected, delete the swap file and start over unless you're sure the last saved version is acceptable.
- To avoid swap files entirely, set 'nobackup' and 'noswapfile' in your .vimrc — but only if you trust your :w habit.
Press 'i' to enter Insert modeType your textKey takeaways
Common mistakes to avoid
3 patternsTyping text while in Normal mode
Trying to quit with Ctrl+C or clicking the X button
Running a find-and-replace like ':%s/old/new' without the trailing '/g' flag
Interview Questions on This Topic
You're SSH'd into a production Linux server and need to edit /etc/nginx/nginx.conf. There's no nano or GUI editor available. Walk me through exactly how you'd open the file, make a change, and save it safely using vim.
Frequently Asked Questions
20+ years shipping production infrastructure and CI/CD at scale. Lessons pulled from things that broke in production.
That's Linux. Mark it forged?
9 min read · try the examples if you haven't