How to do it...

The head command reads the beginning of the input file.

  1. Print the first 10 lines:
        $ head file
  1. Read the data from stdin:
        $ cat text | head
  1. Specify the number of first lines to be printed:
        $ head -n 4 file

This command prints the first four lines.

  1. Print all lines excluding the last M lines:
        $ head -n -M file

Note that it is negative M.

 For example, to print all the lines except the last five lines, use the following command line:

        $ seq 11 | head -n -5
        1
        2
        3
        4
        5
        6

This command prints lines 1 to 5:

      $ seq 100 | head -n 5
  1. Printing everything except the last lines is a common use for head. When examining log files we most often want to view the most recent (that is, the last) lines.
  2. To print the last 10 lines of a file, use this command:
      $ tail file
  1. To read from stdin, use the following command:
      $ cat text | tail
  1. Print the last five lines:
      $ tail -n 5 file
  1. To print all lines excluding the first M lines, use this command:
      $ tail -n +(M+1)

For example, to print all lines except the first five lines, M + 1 = 6, the command is as follows:

      $ seq 100 | tail -n +6 

This will print from 6 to 100.

One common use for tail is to monitor new lines in a growing file, for instance, a system log file. Since new lines are appended to the end of the file, tail can be used to display them as they are written. To monitor the growth of the file, tail has a special option -f or --follow, which enables tail to follow the appended lines and display them as data is added:

    $ tail -f growing_file

You will probably want to use this on logfiles. The command to monitor the growth of the files would be this:

    # tail -f /var/log/messages

Alternatively, this command can be used:

    $ dmesg | tail -f

The dmesg command returns contents of the kernel ring buffer messages. We can use this to debug USB devices, examine disk behavior, or monitor network connectivity. The -f tail can add a sleep interval -s to set the interval during which the file updates are monitored.

The tail command can be instructed to terminate after a given process ID dies.

Suppose a process Foo is appending data to a file that we are monitoring. The -f tail should be executed until the process Foo dies.

    $ PID=$(pidof Foo)
    $ tail -f file --pid $PID

When the process Foo terminates, tail also terminates.

Let's work on an example.

  1. Create a new file file.txt and open the file in your favorite text editor.
  2. Now run the following commands:
        $ PID=$(pidof gedit)
        $ tail -f file.txt --pid $PID
  1. Add new lines to the file and make frequent file saves.

When you add new lines to the end of the file, the new lines will be written to the terminal by the tail command. When you close the edit session, the tail command will terminate.