Terminal Editors — Vim, Nano and Emacs
At 2 a.m. you SSH into web1 to fix one line in the nginx config. There is no graphical editor, no mouse and no VS Code. You get whatever terminal editor is installed, and you need to change the line, save and get out without panic.
The rule
In Vim you are in Normal mode until you ask to type.
Three editors dominate servers:
Nano is the gentlest: you type straight away and the shortcuts are listed at the bottom. Ctrl+O then Enter saves, Ctrl+X exits, Ctrl+W searches.
Vim (or its ancestor vi) is present on almost every Unix-like system, which is why it is worth learning. It is a modal editor:
- Normal mode (where you start): keys are commands.
dddeletes a line,uundoes,/listensearches for "listen",njumps to the next match. - Insert mode: press
iand keys type text. PressEscto go back to Normal. - Command line: from Normal,
:opens a prompt.:wsaves,:qquits,:wqsaves and quits,:q!quits and throws away changes.
Emacs is not modal: you type directly and commands use Control or Alt combinations, such as Ctrl+X Ctrl+S to save and Ctrl+X Ctrl+C to quit. It is powerful and extensible but rarely installed on servers by default.
Tools such as git commit, crontab -e and visudo open the editor named in the EDITOR environment variable, so you can choose:
export EDITOR=nano
sudo nano /etc/nginx/sites-available/notes
sudo vim /etc/nginx/sites-available/notesThe shortcut
Lost in Vim? Press Esc, then type a colon command. Esc always returns you to Normal mode, however many times you press it, and from there :wq or :q! always works.
Open
sudo vim /etc/nginx/sites-available/notes. You are in Normal mode.
The trap: typing text while still in Normal mode. Letters become commands and edit random parts of the file. If that happens, press Esc and u until the damage is undone, or leave with :q!.
Drills
Answer fast — trust the rule.
In Vim, which command quits and discards unsaved changes?
You open a file in Vim and want to start typing text. Which key first?
How do you save and exit in nano?
Which editor are you most likely to find already installed on a minimal Unix server?
Remember
- In Vim you are in Normal mode until you ask to type.
- Shortcut: lost?
Esc, then:wqor:q!. - Trap: typing text in Normal mode; set
EDITORif you prefer nano.
