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.
- ✓Basic programming fundamentals
- ✓A computer with internet access
- ✓Willingness to follow along with examples
- 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.
Vim is a modal text editor that's been a staple of Unix systems since the late 1970s, originally derived from the vi editor. Its defining characteristic is that it doesn't rely on mouse-driven GUIs or constant modifier-key combos — instead, it operates in distinct modes that separate navigation, text manipulation, and command execution.
This design, while initially jarring, lets you keep your hands on the home row and perform complex edits with a few keystrokes once muscle memory kicks in. Vim is not a word processor; it's a tool for raw text manipulation, optimized for speed and precision, and it runs everywhere from embedded Linux devices to your local terminal.
In the modern ecosystem, Vim competes with editors like Neovim (a fork with better plugin architecture and Lua scripting), Emacs (which uses chording instead of modes), and GUI editors like VS Code or Sublime Text. You should use Vim when you need to edit files over SSH, work in environments without a display server, or want an editor that can be fully customized and scripted.
Don't use it if you prefer WYSIWYG editing, need rich formatting like tables and images, or aren't willing to invest the initial learning curve — the first few hours will feel like fighting the tool.
Vim's core innovation is its modal design: Normal mode for navigating and manipulating text, Insert mode for typing, Visual mode for selecting blocks, and Command-line mode for operations like save, quit, or search. Everything else — motions (w, b, j, k), operators (d, y, c), and text objects (iw, ap) — builds on this foundation.
The result is an editor where you can delete a word with daw, change inside quotes with ci", or repeat the last change with . — actions that take seconds in other editors become single keystrokes. This is why Vim remains irreplaceable for sysadmins, developers, and anyone who lives in a terminal.
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.
| Chrome | Firefox | Safari | Edge |
|---|---|---|---|
| ✓ | ✓ | ✓ | ✓ |
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.
# ── Step 1: Open a new file called server_config.txt in vim ── vim server_config.txt # ── You are now in NORMAL MODE (default) ── # Nothing you type will appear as text yet. # The bottom of the screen shows no indicator — that means Normal Mode. # ── Step 2: Press 'i' to enter INSERT MODE ── # You'll see '-- INSERT --' appear at the bottom of the screen. # Now your keystrokes type actual characters. # ── Type this line (you're in Insert Mode now) ── # hostname=web-server-01 # port=8080 # environment=production # ── Step 3: Press Escape to return to NORMAL MODE ── # The '-- INSERT --' indicator disappears. # You are back in 'remote control' mode. # ── Step 4: Press ':' to enter COMMAND MODE ── # A colon ':' appears at the very bottom of the screen. # Type 'wq' then press Enter to Write (save) and Quit. # :wq # ── Back in your terminal ── # Verify the file was saved: cat server_config.txt
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.
# ── Create a sample file to practice navigation on ── cat > deployment_notes.txt << 'EOF' Step 1: Pull the latest Docker image Step 2: Stop the running container Step 3: Remove the old container Step 4: Start the new container with updated env vars Step 5: Run health check on port 8080 Step 6: Tail the application logs Step 7: Confirm deployment is successful EOF # ── Open the file in vim ── vim deployment_notes.txt # ── You are in NORMAL MODE ── # Move down 3 lines: # Press: 3j # Cursor is now on 'Step 4: Start the new container...' # Jump to the end of the current line: # Press: $ # Cursor is now on the 's' of 'vars' # Jump to the start of the current line: # Press: 0 # Cursor is now on 'S' of 'Step 4' # Jump forward 2 words: # Press: 2w # Cursor is now on 'the' # Jump to the last line of the file: # Press: G # Cursor is now on 'Step 7: Confirm deployment is successful' # Jump back to the very first line: # Press: gg # Cursor is now on 'Step 1: Pull the latest Docker image' # Search for 'health': # Press: /health then Enter # Vim jumps to 'Step 5: Run health check on port 8080' # Press 'n' to find the next occurrence (none here, it wraps) # Exit without making changes: # Press: :q then Enter
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.
# ── Create a file with intentional errors to fix ── cat > nginx_config_draft.txt << 'EOF' server { lsten 80; # typo: should be 'listen' server_name example.com; root /var/www/html; index index.html index.htm; location / { try_files $uri $uri/ =404; } # TODO: remove this debug line error_log /var/log/nginx/debug.log debug; } EOF # ── Open the file ── vim nginx_config_draft.txt # ── FIX 1: Correct 'lsten' to 'listen' ── # Navigate to line 2 with: 2G # Move cursor onto 'lsten' with: w (jump one word) # Delete the word with: dw # Enter Insert mode with: i # Type: listen # Press Escape to return to Normal mode # ── FIX 2: Delete the entire '# TODO: remove this debug line' line ── # Search for it: /TODO then Enter # Delete that whole line: dd # ── FIX 3: Also delete the error_log line below it ── # Cursor should now be on the error_log line (dd moves cursor down) # Delete it: dd # ── Undo the last deletion if you made a mistake ── # Press: u # The error_log line comes back # ── Save the file and quit ── # Press: :wq then Enter # ── Verify the result ── cat nginx_config_draft.txt
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.
# ── Scenario: You're editing a Dockerfile on a production server ── vim Dockerfile # ── You make some edits (in Insert mode), then press Escape ── # COMMAND: Save progress mid-edit without closing vim # Press: :w then Enter # Output at bottom: 'Dockerfile' 12L, 310B written # COMMAND: Enable line numbers to cross-reference an error log # Press: :set number then Enter # Line numbers now appear on the left side of every line # COMMAND: Replace every instance of 'node:14' with 'node:20' # Press: :%s/node:14/node:20/g then Enter # Output at bottom: 4 substitutions on 4 lines # COMMAND: Save the updated file to a backup copy first # Press: :w Dockerfile.backup then Enter # Output: 'Dockerfile.backup' 12L, 318B written # (vim stays open on the original Dockerfile) # COMMAND: Save the original and quit vim # Press: :wq then Enter # (back in terminal) # ── Scenario: You open a file, realise you shouldn't change it ── vim /etc/hosts # You accidentally make a change (press 'i', type something, press Escape) # COMMAND: Discard ALL changes and quit — do NOT save # Press: :q! then Enter # (back in terminal — /etc/hosts is completely unchanged) # Confirm the file is unchanged: stat /etc/hosts
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).
# ── Create a sample file ── cat > config_block.txt << 'EOF' server { listen 80; server_name example.com; location / { proxy_pass http://127.0.0.1:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } } EOF # ── Open in vim ── vim config_block.txt # ── Select and indent the location block ── # Move cursor to line starting with 'location' # Press V (line-wise visual mode) — highlights whole line # Press j twice to highlight 3 lines (location, proxy_pass, proxy_set_header lines) # Press > to indent the entire block one level to the right # Press Escape to leave Visual mode # ── Replace 'proxy_pass' in a visual selection ── # Position cursor on 'proxy_pass' line # Press v (character-wise visual mode) # Move to the end of the word 'proxy_pass' with e # Press c to change (delete selected and enter Insert mode) # Type: backend_pass # Press Escape # ── Save the file ── :w # ── Now open another file in the same session ── # :e /etc/hostname # :bn to switch back to config_block.txt # :q to quit the second file # ── Quit vim ── :q
- 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.
// io.thecodeforge # Production server: install and verify Vim sudo apt-get update && sudo apt-get install vim -y vim --version | head -n 2 # Enable line numbers for all files echo "set number" >> ~/.vimrc echo "syntax on" >> ~/.vimrc
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.
// io.thecodeforge # Inside Vim on a config file: # 1. Search for 'error' /error # 2. Replace all occurrences of '192.168.1.1' with '10.0.0.1' in the whole file :%s/192\.168\.1\.1/10.0.0.1/g # 3. Confirm each replacement on lines 20-50 :20,50s/old_config/new_config/gc
\. 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 textType :q! and press Enter (quit without saving)Or :wq to save and quitWhen prompted about swap file, press 'D' to delete itRe-edit the file from scratchOr just :noh (short form)To turn off search highlighting permanently, add 'set nohlsearch' to .vimrc| Action | Normal Editor (nano/gedit) | Vim Command |
|---|---|---|
| Open a file | nano filename.txt | vim filename.txt |
| Start typing text | Just type immediately | Press 'i' first, then type |
| Save the file | Ctrl + S | :w (Command mode) |
| Save and close | Ctrl + X, then Y | :wq |
| Close without saving | Ctrl + X, then N | :q! |
| Delete a whole line | Select + Backspace | dd (Normal mode) |
| Copy a line | Ctrl + C | yy (Normal mode) |
| Paste | Ctrl + V | p (Normal mode) |
| Undo last action | Ctrl + Z | u (Normal mode) |
| Find and replace all | Usually a menu option | :%s/old/new/g |
| Jump to last line | Ctrl + End | G (Normal mode) |
| Jump to first line | Ctrl + Home | gg (Normal mode) |
| Show line numbers | Usually default on | :set number |
| File | Command / Code | Purpose |
|---|---|---|
| vim_modes_demo.sh | vim server_config.txt | Vim's Three Modes |
| vim_navigation_demo.sh | cat > deployment_notes.txt << 'EOF' | Navigating a File in Vim |
| vim_editing_demo.sh | cat > nginx_config_draft.txt << 'EOF' | Editing Text in Vim |
| vim_save_quit_commands.sh | vim Dockerfile | Saving, Quitting and the Commands You'll Use Every Single Da |
| vim_visual_mode.sh | cat > config_block.txt << 'EOF' | Visual Mode and Advanced Editing Techniques |
| install_vim.sh | sudo apt-get update && sudo apt-get install vim -y | Installation and Getting Started |
| search_replace.vim | /error | Search and Replace |
Key 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.
What is the difference between ':q', ':q!', and ':wq' in vim? When would you use each one, and what happens if you use ':q' on a file with unsaved changes?
A junior engineer accidentally ran 'vim /etc/hosts', typed some garbage characters before realising their mistake, and now can't figure out how to exit without saving. What do they do, and how would you explain vim modes to prevent this happening again?
Frequently Asked Questions
Press Escape to make sure you're in Normal mode, then type ':q!' and press Enter. The exclamation mark forces vim to quit and discard all unsaved changes. If you want to save and then quit, use ':wq' instead.
It means you're in Insert mode — the mode where your keystrokes type actual characters into the file, just like a regular text editor. When that indicator disappears, you're in Normal mode, where keys act as commands rather than typing characters. Press 'i' to enter Insert mode, and Escape to leave it.
Vi is the original editor from the 1970s. Vim stands for 'Vi IMproved' — it's a modern, extended version of vi with syntax highlighting, undo history, plugins and much more. On virtually all modern Linux systems, typing 'vi' actually launches vim anyway. Learn vim — all vi knowledge transfers directly, and you get significantly more features.
Use Command mode: type ':%s/old/new/g' and press Enter. The '%' means entire file, 's' is substitute, 'g' means global (all occurrences on a line). Add 'c' at the end to confirm each substitution: ':%s/old/new/gc'.
A swap file (.filename.swp) stores unsaved changes to protect against crashes or session disconnects. It's created automatically when you edit a file. If vim crashes, the swap file can help recover data. If you reconnect and see a swap warning, you can press 'R' to recover, 'D' to delete it, or 'O' to open read-only. For production files, it's often safest to delete it ('D') and re-edit unless you specifically need the recovery.
20+ years shipping production infrastructure and CI/CD at scale. Lessons pulled from things that broke in production.
That's Linux. Mark it forged?
7 min read · try the examples if you haven't