See the first lines of a file with Linux head command

See the first lines of a file with Linux head command

When you troubleshoot or audit a system by handling its log files, it might be useful to get the first lines of them in order to know, the timestamp or date of when the file was created or newly rotated, or to know how was the booting of the system, service or process and if there were any errors.

Thanks to the Linux head command, this is possible by running a simple command, without depending on other more interactive commands like vim or less, or to print it completely with cat command. Therefore, it provides a fast way to print the desired information in a single execution and eliminates any hassle of gathering this initial information.

Printing the start of a file by number of lines using Linux head command

As many other Linux commands, head can be run without any options but followed by the target file name or file path:

$ head long_file
Linux head command example. By default prints the first 10 lines of a target file.

If you don’t use any option, then the default behaviour of head is to print the first 10 lines of the file. Nevertheless, you can change this behaviour with the option -n or –lines option followed by the number of lines you want to print starting from the beginning of the file:

$ head -n 12 long_file
Linux head command example to print a predefined number of lines from the beginning with -n option.
$ head --lines 18 long_file
Linux head command example to print a predefined number of lines from the beginning with --lines option.

As you may appreciate in the above examples, both -n and –lines have the same effect on head command.

Printing the start of a file by number of characters of bytes using head command

Similarly to the print by line count option, there’s the option -c or –bytes options which serves to get a predefined number of characters from the beginning of the target file:

$ head -c 18 long_file
Linux head command example to print a predefined number of bytes from the beginning with --c option.
$ head --bytes 34 long_file
Linux head command example to print a predefined number of bytes from the beginning with --bytes option.

Therefore, we can get a print of a predetermined number of characters or bytes from the beginning of a file by using the options -c or –bytes.

Some thoughts on head command

Unlike the tail command, the head command doesn’t have the -f or –follow option to printed the recent appended lines into the file in real time. That’s fair since the files normally are updated from the end and not from the beginning. That might be the reason that the creators of the command, didn’t implement such option for head similar to tail.