Head And Tail
Part of the Fundamentals section of Coddy's Terminal journey — lesson 30 of 82.
When working with large files, you often don't need to read the entire file — you just need to see the beginning or the end. The head and tail commands let you do exactly that.
The <strong>head</strong> command shows the first lines of a file. By default it shows the first 10 lines:
head log.txtTo specify how many lines to show, use the -n flag:
head -n 3 log.txt # show first 3 lines
head -n 1 log.txt # show only the first lineThe <strong>tail</strong> command shows the last lines of a file. By default it shows the last 10 lines:
tail log.txtTo specify how many lines:
tail -n 3 log.txt # show last 3 lines
tail -n 1 log.txt # show only the last lineWhen to use each:
- Use
headto preview the structure or header of a file - Use
tailto check the most recent entries in a log file
A useful trick — combining both:
You can use both commands together to see the start and end of a file at the same time:
head -n 2 log.txt
tail -n 2 log.txtChallenge
BeginnerUse head and tail to inspect log.txt:
- Print the first 3 lines of the file using
head - Print the last 1 line of the file using
tail
Hint: Use the
-nflag to control how many lines are shown. Run both commands one after the other.
Cheat sheet
The head command shows the first lines of a file (default: 10 lines):
head log.txtThe tail command shows the last lines of a file (default: 10 lines):
tail log.txtUse the -n flag to specify the number of lines:
head -n 3 log.txt # show first 3 lines
tail -n 1 log.txt # show last 1 lineYou can combine both commands to see the start and end of a file:
head -n 2 log.txt
tail -n 2 log.txtTry it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Directories
Create A DirectoryCopy A DirectoryMove And Rename A DirectoryDelete A DirectoryRecap - Directory Operations7File Content
Head And TailWord CountSort CommandUnique CommandGrep BasicsGrep With FlagsRecap - Text Detective2Navigation
Print Working DirectoryList FilesChange DirectoryAbsolute vs Relative PathsHome And Root DirectoryRecap - Find Your Way8Redirection
Standard OutputOverwrite To A FileAppend To A FileStandard InputStandard ErrorRecap - Log Builder6Wildcards And Patterns
The Star WildcardThe Question Mark WildcardBracket WildcardsCombining WildcardsRecap - Selective Operations9Piping
What Is A PipeChaining Two CommandsChaining Multiple CommandsPipe With GrepRecap - Data Pipeline