Unit 2: Reading and checking files · Lesson 2 of 6 · 15 min
Reading part of a file
head, tail and less: the three ways to read files too long for one screen.
mission
- You are
- You are reviewing the end of yesterday and today on web01.
- Situation
- Logs grow all day with the oldest line first. You need the first and last events without scrolling through thousands of lines.
- Goal
- Read the start and end of the account list and the logs.
- Hand in
- The last request of the day and the newest account on the system.
Reading part of a file
- head -n NThe first N lines
- tail -n NThe last N lines
- tail -fFollow new lines as they arrive
- lessPage and search without loading everything
Read the first and last accounts
head -n 3 /etc/passwd root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin bin:x:2:2:bin:/bin:/usr/sbin/nologin tail -n 2 /etc/passwd deploy:x:1003:1003::/srv/app:/usr/sbin/nologin sysops:x:0:0::/root:/bin/bash
you should see New accounts are appended, so tail shows the newest. The last one has the same numbers as root. Hold that thought.
head- Prints the first lines of a file or of piped text. Built into Linux and macOS.
tail- Prints the last lines of a file, or follows it as it grows with -f. Built into Linux and macOS.
Read the edges of the logs
tail -n 1 /var/log/nginx/access.log 192.0.2.58 - - [14/Oct/2026:23:58:56 +0000] "GET / HTTP/1.1" 200 31204 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36" head -n 2 /var/log/auth.log.1 Oct 13 00:17:01 root-lab CRON[405]: pam_unix(cron:session): session opened for user root(uid=0) by root(uid=0) Oct 13 00:17:02 root-lab CRON[405]: pam_unix(cron:session): session closed for user root
defender tip tail -f file keeps printing new lines as they arrive. It is how admins watch a login attempt or a deploy live.
Inside less
| Command | What it does |
|---|---|
Space, b | Next page, previous page |
g, G | First line, last line |
/text | Search. n next, N previous |
q | Quit |
Search inside less
Open the access log, press /, type .git and press Enter. less jumps to the first request for the website's Git folder.
less /var/log/nginx/access.log
you should see A request from 203.0.113.45 at 02:13 for /.git/config. Press q to leave.
less- Shows a long file one screen at a time. Built into Linux and macOS.
What a defender takes away
- 1head for the start, tail for the end, less for everything between.
- 2New lines go at the bottom, so tail shows the latest.
- 3Search in less with /, quit with q.
Questions
0 of 2 solved
Answer each one from what you find on your lab machine.