4.2 Get a part of file (head, tail)



The head command displays the beginning part of file. The tail command displays the end part of file.

4.2.1 Common format

Format

head [option] file-name
tail [option] file-name


file-name is the name of input file to be processed. If the file name is empty or - (hyphen), the data from standard input is processed.

Therefore the following commands are the same meaning.

Example

$ head FILE ↵       Display the beginning 10 lines of the FILE
$ cat FILE | head - ↵       Display the beginning 10 lines of the standard input
$ cat FILE | head ↵       Display the beginning 10 lines of the standard input


The above three commands display the first 10 lines of the file named FILE. Though the 10 lines is the default setting of head command, the number of lines can be changed by option.

4.2.2 The special option -f

The tail command is originally the command to display the end part of file. But the end part of some files are changed often.

The tail command has -f option. Normally, the tail command just displays the end part and exit immediately, but using -f option, it is possible to monitor change on real time.

This option is used often for monitoring a log file. Log file is the output which a service does report its operation status to. When there are any changes in the system or the service operates, its contents are output to the log.

Format

tail -f log-name


You can check changes of the log file on real time.


Practice: Execute tail command


Let's look at how 'tail command and -f option' works actually.

$ ls -l /usr/bin > ls-usr-bin ↵             Preparing ls-usr-bin file


We display the end part of ls-usr-bin.


$ tail ls-usr-bin ↵
            :
            :
            :
-rwxr-xr-x 1 root root 1933 Mar 29 2007 zmore
-rwxr-xr-x 1 root root 3420 Mar 29 2007 znew
lrwxrwxrwx 1 root root 6 Mar 14 22:16 zsoelim -> soelim


The last 10 lines of ls-usr-bin file were displayed.


Practice: Specify the number of end lines (5 lines)


$ tail -n 5 ls-usr-bin ↵
            :
            :
-rwxr-xr-x 1 root root 1933 Mar 29 2007 zmore
-rwxr-xr-x 1 root root 3420 Mar 29 2007 znew
lrwxrwxrwx 1 root root 6 Mar 14 22:16 zsoelim -> soelim


The last 5 lines of ls-usr-bin are displayed. -n is an option to specify the number of lines to output.


Practice: Check the -f option works


$ tail -f ls-usr-bin ↵
            :
            :
-rwxr-xr-x 1 root root 1933 Mar 29 2007 zmore
-rwxr-xr-x 1 root root 3420 Mar 29 2007 znew
lrwxrwxrwx 1 root root 6 Mar 14 22:16 zsoelim -> soelim


The end part is displayed, but control does not come back to shell.
Open another terminal.

echo 'Hello' >> ls-usr-bin ↵


The data is added to the ls-usr-bin file.
Back to the first terminal.
Confirm that 'Hello' is displayed.
Interrupt the process by Ctrl-C, and come back to shell.


Previous Next