Linux commands
Browse topics

Reading the start and end of files with head and tail

Version
unversioned
Review
Draft

Summary#

head prints the beginning of a file and tail prints the end. Both show 10 lines unless you give another count.

Syntax#

sh
head -n 5 file
tail -n 5 file
tail -n +2 file
tail -f logfile
tail -F logfile

tail -f keeps running and prints data appended to the file. Press Ctrl+C to stop it.

Example#

sh
(
  set -eu
  dir=$(mktemp -d)
  trap 'rm -rf -- "$dir"' EXIT
  cd "$dir"
  printf '%s\n' id,name 1,ana 2,binh 3,chi > users.csv

  head -n 2 users.csv
  echo '-- last two lines'
  tail -n 2 users.csv
  echo '-- start at line 2'
  tail -n +2 users.csv
  echo '-- all but the last line'
  head -n -1 users.csv
  echo '-- only line 3'
  head -n 3 users.csv | tail -n 1
)

Expected output#

Text
id,name
1,ana
-- last two lines
2,binh
3,chi
-- start at line 2
1,ana
2,binh
3,chi
-- all but the last line
id,name
1,ana
2,binh
-- only line 3
2,binh

Common mistakes#

tail -n 2 prints the last two lines, while tail -n +2 starts at the second line. When a log is renamed or removed, tail -f keeps following the old open file. Use tail -F to follow the name and retry opening it. It can pick up a replacement created immediately at the same path, but detection may take several seconds when tail polls instead of using inotify.

Version applicability#

This entry describes GNU coreutils head and tail. A negative count such as head -n -1 is not accepted by head on macOS.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0