Skip to content
Published on

Linux head and tail Command Basics

Authors
  • Name
    Twitter

Overview

Linux has useful tools called head and tail. By using these, you can view the beginning or end of a text file.

head document

head
NAME
     head – display first lines of a file

SYNOPSIS
     head [-n count | -c bytes] [file ...]

DESCRIPTION
     This filter displays the first count lines or bytes of each of the
     specified files, or of the standard input if no files are specified.  If
     count is omitted it defaults to 10.

     The following options are available:

     -c bytes, --bytes=bytes
             Print bytes of each of the specified files.

     -n count, --lines=count
             Print count lines of each of the specified files.

     If more than a single file is specified, each file is preceded by a header
     consisting of the string "==> XXX <==" where "XXX" is the name of the file.
tail
NAME
     tail – display the last part of a file

SYNOPSIS
     tail [-F | -f | -r] [-q] [-b number | -c number | -n number] [file ...]

DESCRIPTION
     The tail utility displays the contents of file or, by default, its standard
     input, to the standard output.

     The display begins at a byte, line or 512-byte block location in the input.
     Numbers having a leading plus ('+') sign are relative to the beginning of
     the input, for example, "-c +2" starts the display at the second byte of
     the input.  Numbers having a leading minus ('-') sign or no explicit sign
     are relative to the end of the input, for example, "-n 2" displays the last
     two lines of the input.  The default starting location is "-n 10", or the
     last 10 lines of the input.

     The options are as follows:

     -b number, --blocks=number

examples

Let's assume we have a test.txt file with the following content.

test.txt
$cat test.txt
chaos and order
hello
hi
nice to meet you
and you?
thankyou
1
2
3
4
4
5
6
7
hihihihihi

head file

If you enter a file name after head, it outputs the first 10 lines.

$  head test.txt
chaos and order
hello
hi
nice to meet you
and you?
thankyou
1
2
3
4

head -n file

If you specify a number with -n after head, it outputs the first n lines.

$ head -5 test.txt
chaos and order
hello
hi
nice to meet you
and you?

tail file

Opposite to head, the tail command shows text from the end.

$ tail test.txt
thankyou
1
2
3
4
4
5
6
7
hihihihihi

tail -n file

Specifying -n shows the last n lines.

$ tail -3 test.txt
6
7
hihihihihi

When reading simple text or checking what kind of text it is, it can be very useful to quickly check with tail and head.