Reading files in Linux: cat, head, tail
Updated November 1, 2026
cat prints a whole file, head prints the first lines, and tail prints the last.
Common cases
cat file.txt # the whole file to the terminal
cat -n file.txt # with line numbers
head -n 20 file # the first 20 lines
tail -n 20 file # the last 20 lines
tail -f app.log # follow new lines in real timeSample output
$ cat -n app.log
1 2026-07-19 09:12:04 INFO server started on port 8080
2 2026-07-19 09:12:04 INFO connected to database
3 2026-07-19 09:14:31 DEBUG cache miss for key user:41
...
15 2026-07-19 09:30:00 INFO shutdown signal received
$ head -n 2 app.log
2026-07-19 09:12:04 INFO server started on port 8080
2026-07-19 09:12:04 INFO connected to database
$ tail -n 2 app.log
2026-07-19 09:22:14 INFO worker 3 restarted
2026-07-19 09:30:00 INFO shutdown signal receivedHow it works: cat versus a pager
catdumps the whole file to the terminal at once, so for large files people use the pagerless, which scrolls a page at a time.tail -fdoes not exit: it holds the file open and prints new lines as they arrive. This is the main trick for watching live logs.headandtailread only the edge of the file you ask for, so they stay fast even on gigabyte logs.
Common mistakes
A typo in the file name prints cat: aplog.txt: No such file or directory and returns exit code 1. Point cat at a directory and the message changes: cat: /var/log: Is a directory. cat cannot read a directory; ls lists what is inside.
tail -n 3 and tail -n +3 are different commands. The first prints the last three lines. The second prints everything from line 3 to the end of the file: on a 15-line log that is 13 lines. A plus before the number means 'starting at this line', not 'this many lines'.
tail -f holds on to the file it opened, not to the name. After a rotation, when app.log has been renamed to app.log.1 and a new empty app.log took its place, the command keeps reading the old file: no new lines arrive and the output just looks quiet. tail -F follows the name and reopens the file once it is replaced.
Used in
You need this in the lesson Reading text. The theory is the chapter Reading and editing text.
See also
The less pager, The file command, Redirection > and >>.
Try it
Open the sandbox: a real throwaway Linux terminal in your browser. Run the commands above by hand - the container is deleted when you leave.