In this article, I will introduce you to the head
command. We use head
command to print first part of files.
Sometimes, you don’t want to display the entire contents of the file on the terminal window. You just want to display the first few lines of the file.
About the head command
Table of Contents
The head
command will display the first 10 lines of the file. This is very beneficial in case the file content is too long.
In contrast to the head
command, we have the tail
command used to print the last 10 lines of the file.
Recommended Reading: Use tail command to print last part of files
Syntax of this command.
$ head [options] [file]
Example use head command to print first part of files
Use head command without options
Now that we will do an example, I will use the ls command and combine redirection >
to print out the entire list of files in the /bin
directory into the ls-bin.txt
file.
$ ls /bin > ls-bin.txt
And we count the number of lines with wc command, you will see that the file has 177 lines.
$ wc -l ls-bin.txt
Finally, we use the head
command to display the first 10 lines of this file.
$ head ls-bin.txt
Use head command with options
First, to see all options for the head
command, type the command below.
$ head --help
Next, an option that people often use with that head command is -n
. This option will print number lines you selected immediately after -n
.
Syntax command with -n
.
Recommended Reading: Overview of I/O redirection in Linux
$ head -n [number] [file]
For example, we will only see the first 5 lines of the ls-bin.txt
file
$ head -n 5 ls-bin.txt
Use head command with the pipeline
The head
command is also a command that can handle pipeline data.
Also with the /bin
directory, now we do not give the result to the file but we will display the data right on the terminal with the head
command.
$ ls /bin | head -n 5
Conclusion
This head
command is quite simple, in the next article, we will learn about tail
commands. An order can be considered a brother of the this command.
(This is an article from my old blog that has been inactive for a long time, I don’t want to throw it away so I will keep it and hope it helps someone).