# Editing files: nano, vim, and changing a server safely

Edit config files over SSH with nano and vim, search and replace without mistakes, and change a live server config with a backup, a check and a way back.

Course: [Linux & Bash for DevOps](https://devops.rajeev.pro/courses/linux), lesson 2. About 30 minutes, beginner. Source: https://devops.rajeev.pro/courses/linux/02-editing-files

## What you will learn

- Open, edit, save and quit a file in nano without looking anything up
- Explain vim's modes and move between them on purpose
- Move, delete, copy, paste, search and replace in vim
- Recover from the three things that go wrong (no permission, a swap file, Windows line endings)
- Change a server config safely - back up, edit, validate, reload, verify, and roll back if needed
- Choose the editor that git, crontab and visudo open for you

## Why you edit files in the terminal

Before remote administration, someone could sit at the server and edit a file in a desktop editor. On a
headless production host, the change happens through SSH, often while diagnosing an urgent issue. Copying a
config file to a laptop and back adds steps and risks editing the wrong version.

Terminal editors let you work on the file where the service reads it. They do not make the change safe by
themselves: a typo in an SSH or web-server config can stop a service. Make a backup, edit only the intended
file, review the diff or contents, and validate the service before reloading it.

This lesson uses nano for guided edits and vim for servers where it is the available editor. You'll practise
saving, quitting and changing a server config without turning an edit into an outage.

You need two editors:

| Editor   | Use it when                                        | Why                                                                      |
| -------- | -------------------------------------------------- | ------------------------------------------------------------------------ |
| **nano** | Quick edits, when you're new, when you're nervous  | Every shortcut is printed on screen                                      |
| **vim**  | Everything else, and whenever nano isn't installed | It's on every server, every container image with a shell, and every exam |

You'll also see **Emacs** (powerful, popular with some programmers, rarely installed on servers)
and graphical editors like VS Code, which can edit server files over SSH with its Remote extension.
Both are fine. Neither replaces knowing nano and vim, because the server you're fixing at 2 a.m.
may have only `vi`.

## nano: the editor you can use in a minute

```sh
$ nano notes.txt              # open (or create) a file
$ nano -l notes.txt           # with line numbers, which you'll want when an error says "line 42"
$ nano +42 /etc/hosts         # open with the cursor on line 42
```

> **Figure.** The nano screen: a title bar with the version and file name, the text area, a status line for messages, and two rows of shortcuts at the bottom, where ^ means Ctrl and M- means Alt.
>
> nano prints its own cheat sheet. ^O means Ctrl+O; M-U means Alt+U.

You type, and the text goes in. The keys that matter:

| Do this                  | Press                                                |
| ------------------------ | ---------------------------------------------------- |
| Save                     | Ctrl+O, then Enter to keep the name                  |
| Quit                     | Ctrl+X (it asks to save if anything changed: Y or N) |
| Search                   | Ctrl+W, type, Enter. Alt+W finds the next match      |
| Search and replace       | Ctrl+\\ (or Alt+R)                                   |
| Go to a line             | Ctrl+\_ (newer versions show it as ^/)               |
| Cut / paste a whole line | Ctrl+K / Ctrl+U                                      |
| Undo / redo              | Alt+U / Alt+E                                        |
| Where am I?              | Ctrl+C shows the line and column                     |

> **Keep a backup while you learn.** `nano -B file` saves the previous version as `file~` every time you save. On a server, you'll usually make the backup yourself instead (see below), but it's a good habit on your own machine.

> **Video.** [Nano Text Editor on Linux Basics - How to Use Nano Tutorial (Beginners Guide)](https://www.youtube.com/watch?v=g2PU--TctAM) (SavvyNik)

## vim: learn the modes and the keys follow

vim feels strange for one reason: **the same key does different things depending on the mode.**
In **normal mode** keys are commands (`dd` deletes a line). In **insert mode** keys type text. Once
you always know which mode you're in, vim stops being scary.

> **Figure.** vim's modes. Normal mode is the centre. Press i, a or o to go to insert mode and Esc to come back. Press : for command-line mode, where :w, :q and :%s run, and Enter or Esc brings you back. Press v or V for visual mode to select text, and Esc to return.
>
> Everything goes through normal mode. Lost? Press Esc, and you're home.

```sh
$ vim app.conf                # vim opens in NORMAL mode: keys are commands, not text
$ vimtutor                    # the built-in 30-minute tutorial. Worth every minute
```

On most servers `vi` starts vim (or a small version of it), so everything here works with `vi` too.

> **Video.** [Vim As Your Editor - Introduction](https://www.youtube.com/watch?v=X6AR2RMB5tE) (ThePrimeagen)

### Getting into insert mode, and out

| Key       | Starts typing                  |
| --------- | ------------------------------ |
| `i` / `a` | before / after the cursor      |
| `I` / `A` | at the start / end of the line |
| `o` / `O` | on a new line below / above    |
| `Esc`     | back to normal mode, always    |

### Moving around (normal mode)

| Keys            | Moves                                           |
| --------------- | ----------------------------------------------- |
| `h` `j` `k` `l` | left, down, up, right (the arrow keys work too) |
| `w` / `b`       | next word / back a word                         |
| `0` / `$`       | start / end of the line                         |
| `gg` / `G`      | first / last line of the file                   |
| `42G` or `:42`  | line 42                                         |

Put a number in front of a command to repeat it: `5j` moves down five lines, `3dd` deletes three.

### Changing text (normal mode)

| Keys         | Does                                                           |
| ------------ | -------------------------------------------------------------- |
| `x`          | delete the character under the cursor                          |
| `dd` / `yy`  | cut / copy the whole line ("yank")                             |
| `dw`         | delete to the end of the word                                  |
| `p` / `P`    | paste below / above                                            |
| `u` / Ctrl+R | undo / redo                                                    |
| `v` / `V`    | select characters / whole lines (visual mode), then `d` or `y` |
| `.`          | repeat the last change                                         |

## Search and replace

```text
/listen        search forward for "listen"     n = next match, N = previous
?listen        search backward
:noh           clear the highlight

:s/8080/9090/            first match on this line only
:s/8080/9090/g           every match on this line
:%s/8080/9090/g          every match in the whole file
:%s/8080/9090/gc         every match, asking y/n/a/q for each one
:10,20s/http:/https:/g   only lines 10 to 20
```

`%` means every line, `g` every match on a line, `c` confirm. Use `gc` on anything that matters:
`:%s/80/8080/g` would also turn `8000` into `808000`. If a replace goes wrong, one `u` undoes all of
it. In nano, Ctrl+\\ asks the same questions: what to find, what to replace it with, then Y, N or A
(all) for each match.

> **Figure.** A real vim session on lab2/app.conf after typing :%s/8080/9090/gc. The current match, 8080 on the port line, is highlighted; the next match, in health_url, is highlighted too. The bottom line asks: replace with 9090 (y/n/a/q/l/^E/^Y)?
>
> What :%s/8080/9090/gc really looks like: vim highlights each match and asks before changing it. y replaces, n skips, a replaces the rest, q stops.

## Save and quit safely

| In vim (normal mode)  | Does                                                               |
| --------------------- | ------------------------------------------------------------------ |
| `:w`                  | save                                                               |
| `:wq` or `:x` or `ZZ` | save and quit                                                      |
| `:q`                  | quit (refuses if there are unsaved changes)                        |
| `:q!` or `ZQ`         | quit and **throw away** the changes                                |
| `:w!`                 | save even if the file is marked read-only (when you're allowed to) |
| `:w newname.conf`     | save a copy under another name                                     |

Saving and quitting are separate choices. `:w` writes the current buffer to disk but leaves vim open, which
lets you review again before leaving. `:q` exits only when there are no unsaved changes. Use `:q!` only when
you intend to discard those changes; it does not ask you to confirm every edit afterward.

When you are unsure which mode you are in, press `Esc` before entering a colon command. Vim command-line
commands begin with `:` and run after Enter. If the file is important, make a copy before editing and reopen
the saved file to verify it. A common beginner mistake is pressing `:q!` to get unstuck and losing the work;
use `:wq` when you mean to save and exit.

Three things go wrong sooner or later. Here's what each one means:

> **Permission denied (or vim's E212) when saving.** The file belongs to root. Don't `chmod` it. Quit with `:q!` and edit it the right way: `sudoedit /etc/nginx/nginx.conf`. sudoedit copies the file, opens the copy in **your** editor as you, and writes it back as root when you quit. Your editor never runs as root, so your plugins and settings can't touch system files by accident.

> **E325: ATTENTION. Found a swap file.** vim keeps unsaved work in a hidden file like `.app.conf.swp`. You see this when **someone else has the file open right now**, or an earlier session crashed (a dropped SSH connection, for example). If someone is editing: press `O` to open read-only and talk to them. If it crashed: press `R` to recover, check the text, `:w`, then delete the old swap file (`rm .app.conf.swp`).

> **$'\r': command not found.** The file was saved on Windows, so every line ends with an invisible `\r`. `file script.sh` reports "with CRLF line terminators". Fix it with `sed -i 's/\r$//' script.sh` (or `dos2unix`), or in vim with `:set ff=unix` then `:w`.

## Editing a server's config without breaking it

Editing a service configuration directly can take effect on every user of that service. A safe change has a
rollback path: copy the original, edit the intended file, inspect the change, run the service's validation
command, then reload or restart only if validation passes.

A typo in `nginx.conf` can take a site down. A bad SSH change can lock you out. Use the same five steps for
both services. They give you a rollback before the change reaches users:

> **Figure.** A safe config change in five steps: back up the file, edit it with sudoedit, validate it with the service's own check, reload the service, and verify it works. If the check or the verify step fails, restore the backup and reload.
>
> Never restart on a config you haven't validated. Keep the backup until you've verified.

```sh
$ sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak-$(date +%F)   # 1. back up
$ sudoedit /etc/nginx/nginx.conf                                       # 2. edit
$ sudo nginx -t                                                         # 3. validate
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
$ sudo systemctl reload nginx                                           # 4. reload, not restart
$ curl -sI http://localhost | head -n 1                                 # 5. verify
HTTP/1.1 200 OK
```

Most services have a check for step 3:

| Service      | Check before you reload                                                                         |
| ------------ | ----------------------------------------------------------------------------------------------- |
| nginx        | `sudo nginx -t`                                                                                 |
| SSH          | `sudo sshd -t` (prints nothing when the file is fine)                                           |
| sudoers      | always edit with `sudo visudo`, which refuses to save a broken file; `sudo visudo -c` checks it |
| systemd unit | `systemd-analyze verify myapp.service`                                                          |

If step 3 or step 5 fails, roll back with
`sudo cp /etc/nginx/nginx.conf.bak-2026-10-13 /etc/nginx/nginx.conf` (use your backup's date),
then reload again. `reload` keeps the running service up while it reads the new config; `restart` stops it
first, which is the moment a broken file takes you down.

> **In production: keep your SSH session open.** When you change `sshd_config`, run `sudo sshd -t`, reload SSH, then **open a second SSH session** to check you can still log in, before you close the first one. If the new config locks you out, the old session is your way back in.

## When an editor isn't the right tool

An interactive editor is useful for a person, but a script or deployment pipeline needs repeatable input.
A **here-document** sends a block of text to a command's standard input. Quoting the delimiter keeps the
shell from expanding variables or command substitutions inside the content.

Scripts and pipelines can't press Ctrl+O. To create a file without opening an editor:

```sh
$ cat > ~/lab2/app.conf <<'EOF'
port = 8080
log_level = info
EOF
$ cat ~/lab2/app.conf
port = 8080
log_level = info
```

`<<'EOF'` (a "heredoc") feeds the lines up to `EOF` into the command. The quotes stop the shell
from expanding `$VARIABLES` inside it.

For a file only root may write, `sudo cat > /etc/myapp/app.conf` fails: the `>` belongs to your
own shell, which runs without sudo. Let `tee` do the writing instead:

```sh
$ sudo tee /etc/myapp/app.conf > /dev/null <<'EOF'
port = 8080
EOF
```

For one-line changes in scripts (`sed -i 's/8080/9090/' app.conf`), see the _Text processing_
lesson.

## Choosing your default editor

Programs such as `visudo`, `crontab -e` and Git open the editor named by environment variables such as
`VISUAL` or `EDITOR`. Setting a default avoids learning a different editor for every tool. Choose one you can
exit safely, especially on a remote server where closing the terminal may leave a program waiting.

Set the preference in your shell startup file or for one command only. Check the value before starting an
important edit. Do not point an editor variable at a wrapper or command you do not trust; programs inherit the
environment and may launch it with files you did not expect.

`git commit`, `crontab -e`, `kubectl edit` and many other tools open an editor for you. They pick
it from these variables:

```sh
$ echo 'export EDITOR=nano' >> ~/.bashrc     # or vim
$ echo 'export VISUAL=nano' >> ~/.bashrc     # some tools check VISUAL first
$ source ~/.bashrc
$ git config --global core.editor nano       # git's own setting wins over both
```

On Ubuntu and Debian, `sudo update-alternatives --config editor` sets the system-wide default,
which is why `visudo` opens nano there. `visudo` and `sudoedit` also follow `SUDO_EDITOR`,
`VISUAL` and `EDITOR`.

## Mission: Change an app's port, safely

Your team is moving the app from port 8080 to 9090. The port appears in two places in ~/lab2/app.conf. Create the file, back it up, change every 8080 to 9090 in vim while confirming each match, and prove exactly what changed.

- You need: ~/lab2/app.conf (port 8080, health check on 8080)
- You'll have: ~/lab2/app.conf

```sh
$ mkdir -p ~/lab2 && cat > ~/lab2/app.conf <<'EOF'
name = payments
port = 8080
log_level = info
health_url = http://localhost:8080/health
EOF
$ cp ~/lab2/app.conf ~/lab2/app.conf.bak      # 1. back up
$ vim ~/lab2/app.conf                          # 2. edit: :%s/8080/9090/gc, y, y, then :wq
$ grep -n 9090 ~/lab2/app.conf                 # 3. check the new value is there
2:port = 9090
4:health_url = http://localhost:9090/health
$ diff ~/lab2/app.conf.bak ~/lab2/app.conf     # 4. prove nothing else changed
2c2
< port = 8080
---
> port = 9090
4c4
< health_url = http://localhost:8080/health
---
> health_url = http://localhost:9090/health
```

`diff` is your proof: exactly two lines changed, and they're the right two. If you'd typed
`:%s/80/90/g` by mistake, diff would show more changed lines, and `cp app.conf.bak app.conf` puts
everything back.

## Try it

- Open `~/lab2/notes.txt` with `nano -l`, add three lines, save with Ctrl+O and quit with Ctrl+X.
- In nano, jump to line 2 with Ctrl+_ , cut it with Ctrl+K and paste it at the end with Ctrl+U.
- Run `vimtutor` and finish lesson 1 (about 10 minutes).
- In vim, open the same file, delete a line with `dd`, undo with `u`, then save and quit with `:wq`.
- In vim, replace every `test` with `prod` using `:%s/test/prod/gc` and answer `y` or `n` for each match.
- Set `export EDITOR=nano` in `~/.bashrc`, open a new shell and run `crontab -e` to see which editor opens.

## Quiz

1. You're in vim, you've typed some text, and now you want to save and quit. What do you press?
   - :wq straight away
   - **Esc, then :wq and Enter** (answer)
   - Ctrl+X, then Y
   Why: Commands like :wq only work from normal mode. Esc always takes you back there; pressed while typing, :wq would just become text in the file. Ctrl+X is nano.

2. You edited /etc/nginx/nginx.conf in nano as yourself, and saving fails with "Permission denied". What's the right fix?
   - chmod 777 /etc/nginx/nginx.conf, then save again
   - **Quit without saving and edit it with sudoedit /etc/nginx/nginx.conf** (answer)
   - Save a copy in your home folder and forget about it
   Why: The file belongs to root, which is correct. sudoedit lets you edit it in your own editor and writes it back with root rights. chmod 777 would let every user and process on the server rewrite your web server config.

3. Which vim command replaces every "staging" with "prod" in the whole file, asking before each change?
   - /staging/prod
   - :s/staging/prod/
   - **:%s/staging/prod/gc** (answer)
   Why: % means every line, g means every match on a line, c means confirm. :s/…/…/ alone changes only the first match on the current line.

4. vim opens with "E325: ATTENTION … Found a swap file". What happened?
   - The file is corrupted and lost
   - **Someone else is editing it right now, or an earlier vim session crashed** (answer)
   - The disk is full
   Why: vim keeps unsaved work in a hidden .swp file. Check nobody else has the file open; if a session crashed, press R to recover the unsaved changes, save, then delete the old .swp.

5. A script copied from a Windows laptop fails with "$'\r': command not found". Why?
   - Bash is not installed
   - **The file has Windows line endings (CRLF); each line ends with an invisible \r** (answer)
   - The script needs sudo
   Why: Linux expects lines to end with \n only. Remove the \r with sed -i 's/\r$//' script.sh (or dos2unix), then it runs.

6. You need to create /etc/myapp/app.conf with three lines from a script. Why does sudo cat > /etc/myapp/app.conf fail?
   - **The > redirect runs in your own shell, without sudo, before sudo even starts** (answer)
   - cat cannot write files
   - sudo is not allowed in scripts
   Why: Redirects belong to your shell, which has no permission to write there. Pipe into sudo tee /etc/myapp/app.conf > /dev/null instead: tee is the part that runs as root and writes the file.

## Resources

- [nano cheatsheet (every shortcut on one page)](https://www.nano-editor.org/dist/latest/cheatsheet.html) (GNU nano)
- [The nano manual](https://www.nano-editor.org/dist/latest/nano.html) (GNU nano)
- [vim user manual, chapter 1 (and vimtutor)](https://vimhelp.org/usr_01.txt.html) (vimhelp.org)
- [vim: changing text, including :substitute](https://vimhelp.org/change.txt.html) (vimhelp.org)
- [vim: swap files and recovery](https://vimhelp.org/recover.txt.html) (vimhelp.org)
- [sudo and sudoedit manual](https://manpages.ubuntu.com/manpages/noble/man8/sudo.8.html) (Ubuntu manpages)
- [Git configuration: core.editor](https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration) (git-scm.com)
- [LPIC-1 exam 101, objective 103.8: basic file editing](https://www.lpi.org/our-certifications/exam-101-objectives/) (Linux Professional Institute)
