0
0
Linux CLIscripting~10 mins

head and tail in Linux CLI - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - head and tail
Start
Input File
head: Read first N lines
Output first N lines
tail: Read last N lines
Output last N lines
The commands read a file and output either the first or last N lines, showing the start or end of the file.
Execution Sample
Linux CLI
head -n 3 sample.txt

tail -n 2 sample.txt
Shows the first 3 lines and last 2 lines of the file 'sample.txt'.
Execution Table
StepCommandActionOutput LinesOutput Content
1head -n 3 sample.txtReads first 3 lines3Line1\nLine2\nLine3
2tail -n 2 sample.txtReads last 2 lines2Line4\nLine5
3head -n 3 sample.txtIf file has fewer than 3 lines, outputs all lines2Line1\nLine2
4tail -n 2 sample.txtIf file has fewer than 2 lines, outputs all lines1Line1
5head -n 0 sample.txtReads zero lines, outputs nothing0
6tail -n 0 sample.txtReads zero lines, outputs nothing0
💡 Commands stop after reading requested number of lines or entire file if fewer lines exist.
Variable Tracker
VariableStartAfter head -n 3After tail -n 2After head -n 0After tail -n 0
Output LinesN/A3 lines2 lines0 lines0 lines
Output ContentN/ALine1\nLine2\nLine3Line4\nLine5
Key Moments - 3 Insights
Why does head output fewer lines if the file has less than N lines?
Because head reads up to N lines but stops if the file ends earlier, as shown in execution_table row 3.
What happens if you ask tail or head to output zero lines?
They output nothing, no lines are printed, as shown in execution_table rows 5 and 6.
Does tail read the whole file to get the last lines?
Yes, tail reads from the end to output the last N lines, as shown in execution_table row 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, how many lines does 'head -n 3 sample.txt' output at step 1?
A2 lines
B3 lines
C5 lines
D0 lines
💡 Hint
Check the 'Output Lines' column in execution_table row 1.
At which step does the command output zero lines?
AStep 5
BStep 2
CStep 1
DStep 3
💡 Hint
Look for '0' in the 'Output Lines' column in execution_table.
If the file has only 2 lines, what will 'head -n 3' output according to the table?
A0 lines
B3 lines
C2 lines
DNo output
💡 Hint
See execution_table row 3 about fewer lines than requested.
Concept Snapshot
head and tail commands:
head -n N filename: outputs first N lines
tail -n N filename: outputs last N lines
If file has fewer lines, outputs all lines
-n 0 outputs nothing
Useful to preview start or end of files
Full Transcript
The head and tail commands in Linux let you see the start or end of a file. Head reads the first N lines, tail reads the last N lines. If the file has fewer lines than requested, they output all lines. Asking for zero lines outputs nothing. This helps quickly check file contents without opening the whole file.