Today’s article is about the ‘head’ command. The head command is a tool for viewing a file’s contents (or piped data), starting from the top. There’s not a whole lot to the command, and this will make be a pretty short article that’s fit for a beginner.
The head command has been with us since the heady days of Unix (See what I did there?) and is still a useful command today. In fact, the man page defines it like this:
head – output the first part of files
As you can guess, it does exactly what it says on the tin. There are any number of circumstances when you might want to use it, but I often use it when I don’t remember the exact filename I’m after and just want to see the first few lines of text as a reminder. There are better uses.
Anyhow, there’s not a whole lot to it, but I’ll show you the basics. Like we did recently, let’s see if we can all get started on the same page. So, open your terminal and enter the following:
Doing that will put you in the Downloads directory and will download a text file (it’s perfectly harmless) and it means we are all working with the same settings. You do not need to do this, but it could help.
About The ‘head’ Command:
Seeing as you’ve already got the terminal open, and that you figured it out without me having to repeat it like I do in almost every article, we’ll just jump right into the first command.
That should output the first ten lines of the rnd-num.txt file, looking something like this:
That’s the first ten lines from the rnd-num.txt file or, in other words, the head of the file has been outputted to the terminal. This has a number of uses, including the pipe. You can easily pipe it to another command. It’d look something like this:
That’s not all that head can do, it can output a specified number of lines. To do that, you use the -n flag. It looks like this:
You can also use the -c flag to show the first x-number of bytes in a file. That’s not very complicated. In this case, we’ll look at the first 25 bytes.
You’ll find the output looks pretty similar to the output from the previous head command. You can even work with multiple files and the head command will handle them easily. If you’re going to use multiple files, you should use the -v flag.
It’ll helpfully preface the start of each file with the name of the file. In this case, the first line of the output would look like this:
See? Pretty helpful!
As shown in the image, you can easily deal with multiple files and whatnot, but there’s really not much more to be done with the head command. If you’re curious, you can also enter
man head to get more usage information.
Yup… There’s another article. This is about the head command, a command that’s not used often but worth having in your toolbox. If you use it more often, feel free to leave a comment explaining what you do with it.