Skip to content

~/avetyan.com/cheatsheets

Cheat sheets

head and tail cheat sheet

Show the first or last lines or bytes of a file, follow logs that rotate, skip headers and cut out a range of lines with head and tail.

2 min read


bash
head file                               # first 10 lines
head -n 20 file                         # first 20
head -n -5 file                         # all but the last 5 (GNU)
head -c 100 file                        # first 100 bytes
head -n 1 *.csv                         # header of each file, with names
head -q -n 1 *.csv                      # without the file names

tail

bash
tail file                               # last 10 lines
tail -n 50 file
tail -n +2 data.csv                     # from line 2: skip a header
tail -c 1K file                         # last kilobyte

Follow a log

bash
tail -f app.log                         # follow this file
tail -F app.log                         # follow the name: survives rotation
tail -F /var/log/nginx/{access,error}.log
tail -n 0 -F app.log                    # only new lines
tail -F app.log --pid=1234              # stop when that process exits
tail -F app.log | grep --line-buffered ERROR
FlagWhat it does

Use -F for logs. With -f, tail keeps watching the old rotated file and goes quiet.

Ranges

bash
head -n 20 file | tail -n 5             # lines 16–20
sed -n '16,20p' file                    # the same, one process
sed -n '100p' file                      # only line 100
awk 'NR>=16 && NR<=20' file
tail -n +100 file | head -n 10          # 10 lines from line 100

In pipes

bash
ps aux --sort=-%mem | head -n 6         # header plus top 5
du -sh * | sort -rh | head
ls -t | head -n 1                       # newest file
journalctl -u nginx -n 50 --no-pager    # journald's own tail
dmesg | tail -n 20

head closes the pipe after it has enough lines, so the command before it may print “Broken pipe”. That’s harmless.

Keep in mind

  • tail -f on a huge file is cheap; it seeks to the end instead of reading everything.
  • less +F file follows a file like tail -f, and Ctrl-C lets you scroll back and search.

Comments

Sign in with Google, GitHub or Facebook to comment.

Loading comments…