Module 2: Working with Files and Text

7. Editing in the terminal: nano and vim survival

Description

By the end of this lesson you will be able to open a file directly from the terminal, write a line into it, search for text inside it, save it, and quit — with nano, unassisted. And if you end up inside vim without having asked for it, you will know how to get out alive: understanding why you cannot type right away, how to enter write mode, and how to save or discard the change without force-closing the window.

This matters the day you least expect it. You are the on-call engineer, it is two in the morning, nginx is returning 502 in production, and you SSH into the server. There is no VS Code in there: there is a terminal and a configuration file you need to touch right now. Or something simpler: you run git commit with no -m, and with no warning your screen fills with lines starting with ~ on the left and it does not react to anything you type. Both cases are the same problem — you need to edit text without leaving the terminal — and both have a tool built exactly for that.

Connection to the module: in the previous lesson you used grep to find the exact line you cared about inside an entire project. But finding is not the same as fixing: grep tells you where the needle is, it does not let you pull it out of the haystack. This lesson closes that loop. It is also the last loose piece before the module's project, where you are going to combine everything you learned — creating structure, copying and deleting with judgment, reading whole files, finding them, searching inside them, and now editing them — into a single real audit.

When to edit from the terminal (and when not to)

Think of it as the difference between a precision screwdriver and your entire toolbox. The precision screwdriver is exactly what you need for one specific screw, on an engine you cannot haul your whole toolbox to — but nobody builds an entire piece of furniture with it. A terminal editor is your precision screwdriver: perfect for touching one specific file on a machine where you do not have (or do not want) a graphical interface. Your usual editor — VS Code or whatever you use — is the full toolbox: autocompletion, built-in version control, extensions, and the ability to have twenty files open at once. For your real project, that toolbox always wins.

ScenarioTerminal editor?
Adjusting one line of nginx.conf on a remote server over SSHYes — it is the only thing available
Changing a variable in a .env inside a containerYes — fast, you do not need more
crontab -e, sudo visudo, a git commit with no -mYes, even if you did not ask for it — the system forces it on you
Working on your full project, with dozens of filesNo — your usual editor

The middle row is the one that surprises people the first time: there are commands that open a terminal editor on their own, without you having typed nano or vim. Come back to this later in this same lesson.

nano: create, write, search, save, and quit

nano is the terminal editor built so you do not have to learn anything before using it: you open it, you type, and the help you need is always visible on screen, on the last line. That is its whole promise — no modes to memorize, no hidden commands. What you see is what there is.

Worked example: editing a configuration file with nano

You are connected over SSH to a remote server and want to add an alias to your ~/.bashrc.

nano ~/.bashrc

What to expect (the screen fills up completely; this is what you would see, with your file's real content in the middle):

GNU nano 9.1                        /home/ana/.bashrc

# ~/.bashrc: executed by bash(1) for non-login shells.

export PATH="$HOME/.local/bin:$PATH"



^G Help    ^O Write Out ^W Where Is  ^K Cut       ^X Exit

Read that last line as the tool's map: ^ means Ctrl, and the letter that follows is the shortcut. ^G Help is Ctrl+G to ask for help, ^O Write Out is Ctrl+O to save, and so on for each one. Nano always shows you the available shortcuts on screen — you do not need to memorize them going in, just know how to read that bar.

  1. Moving around and writing. Use the arrows to go down to the last line with content and add a new one:

    alias gs='git status'

    As soon as you type something, nano marks the file as modified (it shows this in the header, next to the name).

  2. Searching for existing text. Press Ctrl+W (Where Is). Nano asks for the term at the bottom:

    Search: PATH
    

    Type PATH and press Enter — the cursor jumps to the first match. If there are several, Ctrl+W and Enter again repeats the last search and moves to the next one.

  3. Saving. Press Ctrl+O (Write Out). Nano confirms the file name before writing:

    File Name to Write: /home/ana/.bashrc
    

    Press Enter to confirm that same name and the file gets saved to disk. Careful: Ctrl+O saves, but it does not take you out of the editor.

  4. Quitting. Press Ctrl+X (Exit). Since you already saved in the previous step, nano closes right away and hands you back the prompt. If instead you tried to quit with unsaved changes, nano asks before losing anything:

    Save modified buffer?
     Y Yes
     N No           ^C Cancel
    

    Y saves and quits, N discards the change and quits, Ctrl+C takes you back to the file without deciding yet.

With those four moves — writing, Ctrl+W to search, Ctrl+O to save, Ctrl+X to quit — you cover 90% of real nano usage. The rest of the bar (Ctrl+K to cut a line, Ctrl+U to paste it, Ctrl+_ to jump to a line number) you pick up along the way, always visible on screen.

One detail if you are on macOS: the nano command in your Terminal might actually be pico (its ancestor from the 90s), not GNU nano — Apple stopped updating it years ago over a license change. The shortcuts you just saw work the same, because nano was born as a clone of pico. If you want the full, up-to-date GNU nano, brew install nano takes care of it.

Going deeper: vim survival

Nobody decides to learn vim on some random Tuesday. It arrives the same way for almost everyone: they run a command, the terminal switches screens, and suddenly they are trapped in something that does not respond the way they expected. That is exactly what is going to happen to you, so let us prepare the exit before the entrance.

Think of vim as a walkie-talkie with a talk button. As long as you do not press it, you are in Normal mode: every key you touch is a command — moving around, deleting a line, copying, undoing. None of what you press gets written into the file. When you press the button — in vim, the i key — you enter Insert mode: now every key you touch does get written as text, just like in any normal editor. You let go of the button with Esc, which takes you back to Normal mode from anywhere. There is a third mode, command-line mode, which you enter by typing : from Normal mode — that is where you save and quit.

What breaks beginners is this: vim always opens in Normal mode, never in Insert. If you start typing your text right away, you are actually running commands, one letter at a time.

ModeWhat keys mean thereHow you enter itHow you get back to Normal
Normal (the starting mode)Commands: move, delete, copy, undoThis is how vim always opensyou are already in it
InsertText: gets written as-is into the filei from NormalEsc
Command-lineCommands with : — save, quit: from NormalEnter runs it and returns to Normal

With that as a map, these are the commands you need to survive any encounter with vim:

CommandWhat it does
ienters Insert mode, right where the cursor is
Escreturns to Normal mode from any other mode
:wsaves (write) without quitting
:qquits — only works if there are no unsaved changes
:wqsaves and quits
:q!quits without saving, discards any changes
gggoes to the file's first line
Ggoes to the file's last line
uundoes the last change

Why does vim open without you asking for it? Several everyday commands hand off text editing to "the editor configured on your system" — the $VISUAL or $EDITOR variable, or Git's core.editor setting. When none of those is defined (which is the default situation on a huge number of installs), the system falls back to vi — vim's ancestor, and in practice vim itself on almost any modern machine. The most common triggers you are going to run into:

  • git commit with no -m — opens the editor for you to write the message.
  • git rebase -i — opens the editor for you to reorder or edit commits.
  • crontab -e — opens the editor for you to edit your scheduled tasks.
  • sudo visudo — opens the editor to safely edit sudo permissions.

None of these commands "chose" vim at random: they inherited the lack of configuration, and the system fell back to its default option.

Worked example: surviving a commit that opens vim

git add README.md
git commit

What to expect (the terminal switches screens entirely and shows something like this):

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# On branch master
# Changes to be committed:
#	modified:   README.md
#

You are in Normal mode. If at this point you start typing your message directly, what happens is not what you expect: for example, typing d twice in a row (dd) would delete the line the cursor is on, not write the letters "d" and "d." This is exactly the point where you need to stop and follow the mode model.

  1. Press i to enter Insert mode. You will not see a big visual change, but -- INSERT -- appears in the bottom-left corner.

  2. With the cursor on the first line (above the comments), type your message:

    fix: correct typo in README
    
  3. Press Esc to return to Normal mode.

  4. Type :wq and press Enter — saves the message and quits.

Vim closes and hands you back to the terminal, where Git confirms the commit:

[master 3f2a9c1] fix: correct typo in README
 1 file changed, 1 insertion(+), 1 deletion(-)

If instead you had changed your mind and wanted to abort the commit without saving anything, the exit is Esc and then :q! — Git interprets that you wrote no message and cancels the commit with no complaints.

Common mistakes

Typing right away, without knowing vim starts in Normal mode (conceptual). It is stumbling block number one: someone opens vim (sometimes without having asked for it, like in the commit example) and starts typing their text directly, letter by letter. Since it is in Normal mode, every letter is a command: x deletes the character under the cursor, dd deletes the whole line, o opens a new line below and that one does enter Insert (which confuses people even more, because it seems to "sometimes work"). You spot it because you do not see -- INSERT -- in the bottom-left corner and the file's content changes in a way you did not expect. You fix it with Esc to make sure you are in Normal, u as many times as it takes to undo what broke, and only then i before typing.

Confusing Ctrl+O (save) with Ctrl+X (quit) in nano, without reading the prompt. Ctrl+O is "Write Out" — save — and Ctrl+X is "Exit" — quit; they are different actions, even though it feels natural to think one key should be enough. If you press Ctrl+X with unsaved changes, nano asks "Save modified buffer? Y/N" before losing anything, but it is easy to answer without reading and lose the change you thought you had made. You spot it by checking the file after quitting (cat file) and noticing the change is not there. You fix it by always saving explicitly with Ctrl+O and confirming the name with Enter, and only quitting afterward with Ctrl+X — at that point it quits directly, because there is nothing pending left.

Seeing E37: No write since last change in vim and force-closing the terminal. You try :q with unsaved changes and vim refuses, showing literally E37: No write since last change (add ! to override). In a panic, some people close the terminal tab or kill the SSH session, which can leave the vim process hanging on the server's side instead of resolved. You spot it by that exact message in the status line. You fix it by deciding deliberately: :wq if you want to save the change, or :q! if you want to discard it — you never need to force-close the window.

Exercises

1. The complete nano flow

With nano, create a file called notes.txt with these two lines:

task: write the report
task: review the pull request

Then search for the word review, save the file, and quit. Write the full sequence of commands and shortcuts, in order.

See solution
nano notes.txt

You type the two lines as-is. Then:

  1. Ctrl+W (Where Is) → type review → Enter. The cursor jumps to the match.
  2. Ctrl+O (Write Out) → Enter to confirm the name notes.txt.
  3. Ctrl+X (Exit) → since you already saved, it closes directly with no question asked.

Why it works: each shortcut has a separate job — searching does not save, saving does not quit — and nano never takes you out without warning if something is unsaved, so the save-before-quitting order is what avoids losing your work.

2. The panic button in vim

You end up inside vim by accident — for example, you typed vim instead of another command by mistake. You see an empty file, with columns of ~ on the left, and the status line says "scratch.txt" [New File]. You do not want to change or create anything. What key sequence do you use to quit?

See solution
Esc
:q!
Enter

Esc makes sure you are in Normal mode (in case you accidentally hit some key that put you into Insert). :q! quits without checking for pending changes and without saving anything.

Why it works: even if you are not sure whether you touched something by accident, :q! does not ask or negotiate — it discards any change in the buffer and closes, so it is the safe exit when all you want is to leave no trace.

3. The commit message, step by step

You ran git commit with no -m and vim opened showing the COMMIT_EDITMSG file, with several lines starting with # (Git's comments) and the rest empty. You want to leave the message fix: correct typo in README. Write the full key sequence.

See solution
i
fix: correct typo in README
Esc
:wq
Enter

i enters Insert with the cursor on the first line (above the comments). You type the message. Esc returns to Normal. :wq saves the file and quits.

Why it works: Git ignores every line starting with # and takes the first real line as the commit message; upon saving and quitting, Git regains control and completes the commit with that text.

4. Explain the mode model in your own words

Why is pressing dd in Normal mode not the same as "typing the letters d and d"? Explain the difference using vim's mode model.

See solution

In Normal mode, keys are never interpreted as text: they are commands. d is the "delete" command, and repeating it (dd) is a vim shortcut for "delete the entire line the cursor is on." There is never a moment where those two keystrokes turn into the character "d" written twice into the file — for that to happen, you would have to be in Insert mode, entering with i first.

Why it works: the same physical key on the keyboard means something completely different depending on the active mode; that is why vim feels unpredictable to someone who does not know what mode they are in, and also why it is so fast for someone who does — a two-key command replaces what in another editor would be selecting the line and deleting it with the mouse.

Summary and next step

Before moving on you should be able to:

  • decide whether a file gets edited from the terminal or in your usual editor, based on where you are standing and how much you are going to touch;
  • open, write, search (Ctrl+W), save (Ctrl+O), and quit (Ctrl+X) nano unassisted, reading the shortcut bar that is always on screen;
  • recognize that vim opens in Normal mode, enter Insert with i, return with Esc, and save or quit with :w, :q, :wq, or :q!;
  • move from one end of a file to the other in vim with gg and G, and undo a change with u;
  • get out of vim alive when it opens without you asking for it — a git commit with no -m, a crontab -e — without force-closing the terminal.

You now have the module's seven pieces: creating structure with mkdir and touch, copying/moving/deleting with safety judgment, reading files of any size, finding them with find, searching inside them with grep, and now editing them without leaving the terminal. The project that follows does not teach you anything new — it pulls those seven pieces together to reconstruct and audit, with evidence, a project you do not know.

Resources