Linux Labs

First steps / Stage 9 of 15

Text and editors

Not running Starting usually ~20 s
Leave the lesson

Step 2 of 8 · theory · 4 min

The start, the end and a live log

Nobody reads a log of thousands of lines in full: you usually need the start, the end, or whatever is being written right now.

cat prints a whole file, which suits a short config. With a log of thousands of lines, the start scrolls off the screen. A long file is read in less from the lesson "Working comfortably in the terminal", or in parts:

bash
head -n 3 service.log   # first 3 lines
tail -n 5 service.log   # last 5 lines
tail -f service.log     # the end, then new lines as they arrive

Without -n, both commands show 10 lines. The last lines are last by position in the file. A log appends new records at the end, so that is usually where the fresh events are.

tail -f (f for follow) shows the end of the file and does not exit: it waits for lines to be appended and prints them at once. If no new records come, the terminal looks frozen: tail is waiting. Ctrl+C gets you out.

Check yourself 1 question

The service log has 50,000 lines. A colleague is about to restart the service, and you need to see what it writes. What do you run?

  • cat prints all 50,000 lines, and you have to dig the restart records out of the end of the output. cat cannot wait for new lines: it prints the file and exits.

  • It shows the last lines as of now, and the restart records appear later. tail -f prints lines as they are written.

  • head shows the start of the file, while a log appends new records at the end. Compare head -n 2 service.log with tail -n 2 service.log.

tail -f shows the end of the log and prints the lines the service appends later. Once you have seen what you need, leave with Ctrl+C.

Key points

  • head and tail with -n show the start and the end of a file; without -n, 10 lines each.
  • tail -f prints new lines as they are written and waits until you press Ctrl+C.
Ubuntu 24.04
Loading…