# Read and edit files on Linux (cat, less, tail, nano, vim)

> On a Linux server you read files with cat, less, head and tail, edit them with nano or vim, and always copy a config file to a backup before you change it.

URL: https://levelrail.com/learn/linux/read-and-edit-files-on-linux/
Updated: 2026-11-27

Most server work is reading a file to see what is wrong, then changing a few lines of config. You need a way to view long files without flooding the screen, follow a log as it grows, and edit text over SSH where there is no mouse. This lesson covers the tools that do that, and the one habit that saves you: back up before you edit.

## How it works

Every tool here works on plain text files. Viewers (`cat`, `less`, `head`, `tail`) only read. Editors (`nano`, `vim`) change the file, and they save by writing the whole file back. Files under `/etc` are owned by root, so you edit them with [sudo](https://levelrail.com/learn/glossary/#sudo)) or `sudoedit`. Where files live is covered in [Linux filesystem layout](https://levelrail.com/learn/linux/linux-filesystem-layout/)).

When a service reads its config only at start, your edit has no effect until a reload or restart. That is a common reason a change "does not work".

## Step 1: Read files

```bash
cat /etc/hostname
less /var/log/syslog
head -n 20 /etc/ssh/sshd_config
tail -n 50 /var/log/auth.log
```

`cat` prints the whole file, so use it for short files only. `head -n 20` prints the first 20 lines and `tail -n 50` prints the last 50. Logs are written at the end, so `tail` is the one you use most.

`less` opens a pager. Useful keys:

- Space or `f` moves down a page, `b` moves up.
- `/word` searches forward, `?word` searches backward, `n` jumps to the next match.
- `G` goes to the end, `g` to the start.
- `q` quits.

Inside `less`, press `F` (capital) to follow the end of the file like `tail -f`, and Ctrl+C to stop following. Some files, such as `/var/log/auth.log`, need `sudo` to read.

## Step 2: Follow a log live

```bash
sudo tail -f /var/log/nginx/error.log
sudo tail -n 100 -f /var/log/syslog
```

`tail -f` keeps the file open and prints new lines as they arrive. Leave it running in one terminal while you restart a service or send a request in another, then press Ctrl+C to stop. If a log is rotated, `tail -F` (capital) reopens the new file instead of staying on the old one. For services that log to the journal instead of files, use [journalctl](https://levelrail.com/learn/server-basics/read-logs-with-journalctl/)). More on [logs](https://levelrail.com/learn/glossary/#logs)) in the glossary.

## Step 3: Back up a config before you edit

```bash
sudo cp -a /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
```

`cp -a` keeps owner, permissions and timestamps. Put the backup next to the original with a clear suffix, or add a date such as `sshd_config.2026-11-27`. To undo a bad edit:

```bash
sudo cp -a /etc/ssh/sshd_config.bak /etc/ssh/sshd_config
```

Compare your change against the backup with `diff`:

```bash
diff /etc/ssh/sshd_config.bak /etc/ssh/sshd_config
```

Lines starting with `<` are from the backup and `>` are from the edited file. Never skip the backup on a file that can lock you out, such as `sshd_config`, `/etc/fstab` or `/etc/sudoers`. Keep a second SSH session open while you test SSH changes.

## Step 4: Edit with nano

```bash
sudoedit /etc/ssh/sshd_config
sudo nano /etc/hosts
```

nano shows its shortcuts at the bottom, where `^` means Ctrl. The ones you need:

- Type to insert text, and use the arrow keys to move.
- Ctrl+O then Enter saves ("Write Out").
- Ctrl+X exits. If there are unsaved changes, it asks `Save modified buffer?`. Press `y` then Enter, or `n` to discard.
- Ctrl+W searches. Ctrl+K cuts a line and Ctrl+U pastes it.
- Ctrl+_ then a line number jumps to that line (on some terminals use Alt+G).

`sudoedit file` (or `sudo -e file`) is safer than `sudo nano file`. It runs the editor as you, on a temporary copy, and writes the result back to the root-owned file only when you save. Choose the editor with `export EDITOR=nano` or `sudo update-alternatives --config editor`.

## Step 5: Survive vim

vim is installed almost everywhere, and you will land in it by accident (for example, from `crontab -e` or `git commit`). It has modes, which is why it confuses people.

```bash
sudo vim /etc/hosts
```

1. vim starts in normal mode, where keys are commands. Do not just type.
2. Press `i` to enter insert mode. `-- INSERT --` appears at the bottom. Now you can type.
3. Press `Esc` to return to normal mode.
4. Type `:wq` and Enter to save and quit, or `:q!` and Enter to quit and throw away changes.
5. Other useful commands in normal mode: `/word` to search, `dd` to delete a line, `u` to undo, `:set number` to show line numbers.

If you are stuck, press `Esc` a couple of times, then type `:q!` and Enter. A read-only file refuses `:wq`, and `:w !sudo tee %` is the trick to write it with sudo, but exiting and reopening with sudoedit is clearer.

## Check it worked

```bash
diff /etc/ssh/sshd_config.bak /etc/ssh/sshd_config
sudo sshd -t && echo "config ok"
sudo systemctl reload ssh
```

`sshd -t` tests the config and prints nothing when it is valid. Many services have a similar check, such as `nginx -t`. Only reload after the test passes. Then confirm the new setting is live, for example by opening a second SSH session before closing the first.

## Edge cases and gotchas

- **Two editors on one file.** If another session edits the same file, the last save wins. Check with `ls -l` and the timestamp.
- **Swap files in vim.** A `.swp` file next to the original means vim crashed or another session has the file open. Check before you delete it.
- **Invisible whitespace breaks some formats.** YAML wants spaces, not tabs. Makefiles need tabs. Use `cat -A file` to show tabs (`^I`) and line endings (`$`).
- **Windows line endings.** A script copied from Windows can show `bad interpreter: /bin/bash^M`. Convert it with `sed -i 's/\r$//' script.sh`.
- **Editing a file a service is writing.** For a live log, never edit it. Use `tail` to read and logrotate to trim.
- **sudo with redirects.** `sudo echo x > /etc/file` fails because the redirect runs as you. Use `echo x | sudo tee /etc/file`, explained in [pipes, redirects and xargs](https://levelrail.com/learn/linux/pipes-redirects-and-xargs/)).

## Troubleshooting

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| `Permission denied` when saving in nano | You opened a root-owned file without sudo | Quit, then use `sudoedit file` |
| vim shows `E45: 'readonly' option is set (add ! to override)` | File opened read-only or no write permission | `:q!`, reopen with `sudoedit`, or `:w !sudo tee %` |
| vim shows `E325: ATTENTION` and `Found a swap file` | Another session or a crash left a swap file | Press `Q` to quit, check for other sessions, then delete the `.swp` if stale |
| `nano: command not found` | nano is not installed | `sudo apt install nano`, or use `vi` |
| `less: /var/log/auth.log: Permission denied` | Log is readable by root or adm only | Use `sudo less /var/log/auth.log` |
| `tail: cannot open 'file' for reading: No such file or directory` | Wrong path or log not created yet | Check with `ls /var/log`, and confirm the service logs to a file |
| `sshd_config line 12: Bad configuration option` | Typo in the edit | Fix the line, or restore the `.bak` copy, then run `sshd -t` again |
| Edit has no effect | Service not reloaded, or a later file overrides it | Reload the service, and check include folders such as `sshd_config.d/` |

## Quick reference

```bash
cat file                      # whole file
less file                     # pager: / search, n next, q quit
head -n 20 file               # first 20 lines
tail -n 50 file               # last 50 lines
sudo tail -f /var/log/syslog  # follow live
sudo cp -a file file.bak      # back up first
sudoedit /etc/file            # edit as root, safely
diff file.bak file            # review changes
# nano: Ctrl+O save, Ctrl+X exit
# vim:  i insert, Esc, :wq save, :q! discard
```

## Related lessons

- [Work with files safely](https://levelrail.com/learn/linux/work-with-files-safely/)): copy, move and search before you edit.
- [Read logs with journalctl](https://levelrail.com/learn/server-basics/read-logs-with-journalctl/)): the log tool for systemd services.
- [Essential Linux commands for servers](https://levelrail.com/learn/server-basics/essential-linux-commands-for-servers/)): the wider command set this builds on.
- [Create a sudo user](https://levelrail.com/learn/server-basics/create-a-sudo-user/)): the account you need to edit system files.
- [Linux file permissions explained](https://levelrail.com/learn/server-basics/linux-file-permissions-explained/)): why saving a file can fail.

For editing app secrets without leaking them, see [manage secrets in self-hosted Docker](https://levelrail.com/blog/manage-secrets-self-hosted-docker/)).

## Next

Files are only half of a server. Next, see what is running on it in [processes and signals](https://levelrail.com/learn/linux/processes-and-signals/)).

## Frequently asked questions

### How do I exit vim?

Press Esc, then type :q! and Enter to quit without saving, or :wq and Enter to save and quit. If nothing seems to happen, Esc first to leave insert mode.

### How do I save and exit nano?

Press Ctrl+O then Enter to write the file, then Ctrl+X to exit. If you exit with unsaved changes, nano asks whether to save.

### How do I follow a log file live in Linux?

Run tail -f /path/to/file to print new lines as they are written, and press Ctrl+C to stop. Use tail -n 100 -f to start with the last 100 lines.

### How do I edit a root-owned file safely?

Use sudoedit /etc/file or sudo -e. It copies the file to a temporary location, opens it in your own editor, and writes it back when you save.


## Sources

- [GNU nano manual](https://www.nano-editor.org/dist/latest/nano.html)
- [Ubuntu manpages, sudoedit](https://manpages.ubuntu.com/manpages/noble/en/man8/sudo.8.html)
