DEV Community

Damon Marc Rocha II
Damon Marc Rocha II

Posted on

The Head and Tail of bash

Alt text of image

Heads and Tails are not limited to the sides of a coin. In bash, these two words can be used to read from a file straight to your terminal. I found these two commands to be really useful recently and have been using them consistently.


Starting with head, this command allows you to read a file into your terminal starting from the beginning. By default, the first twenty lines are read but there are ways to modify this.

head [filename] //=> First 20 lines
head -n 11 [filename] //=> First 11 lines  
head -30   [filename] //=> First 30 lines 
head -c 20 [filename] //=> First 20 characters  
Enter fullscreen mode Exit fullscreen mode

The code above shows four different implementations of the head command along with the line flag(-n) and the character flag(-c).
These can be combined with other commands to display some unique terminal outputs. More Here


Now onto tail; this command is similar to head but instead of reading from the beginning of the file it starts at the end. The default, like head, reads the first 20 lines from the end. The example below shows some basic uses of tail.

tail [filename] //=> Last 20 lines
tail -n 11 [filename]  //=> Last 11 lines  
tail -30   [filename] //=> Last 30 lines
tail -c 20 [filename] //=> Last 20 characters  
Enter fullscreen mode Exit fullscreen mode

More Here


By combining these commands it is possible to get sections of the text that do not start at the beginning or end. The example below reads a file from line 12 to line 22.

head -22 [filename] | tail -11 [filename]
Enter fullscreen mode Exit fullscreen mode

Using the '|' between the two commands works as an 'and' operator so that the only lines read are those that are in the first 22 and the last 11 lines of the file. This results in terminal reading lines 12-22.

Top comments (1)

dulyaaa profile image
Dulya Perera

Do you know the meaning of this command tail –5 abc.txt >> headtail. Here I'm trying to get last 5 records in 'abc.txt' file.
I just know only this command which is tail –5 abc.txt > headtail which will give the output of last records in file.

What will be this one >> do?

Thank you.