Beginner · 6 min · practise every command in the built-in terminal

head and tail

For large files, you often just need the beginning or end.

head — First lines

head /etc/passwd          # First 10 lines (default)
head -n 20 /etc/passwd    # First 20 lines
head -5 /etc/passwd       # First 5 lines

tail — Last lines

tail /var/log/syslog      # Last 10 lines
tail -n 50 /var/log/syslog   # Last 50 lines
tail -f /var/log/syslog      # Follow: real-time updates!

The -f flag is incredibly useful for monitoring logs in real time.

Combining head and tail

# Print lines 10-20 of a file:
head -20 file.txt | tail -10

Practical uses

tail -f /var/log/nginx/access.log       # Watch web server requests live
head -1 data.csv                        # Check CSV headers
tail -n +2 data.csv                     # Skip header line (print from line 2)

Practice tasks

  1. Show the first 5 lines of /etc/passwd
  2. Show the last 3 lines of /etc/passwd
  3. Show only the first line of README.txt
  4. Print lines 10-20 of /etc/passwd by combining head and tail

Commands in this lesson

Reading Files