head (display first part of files)
The head command is a utility that outputs the beginning portion of files. By default, it displays the first 10 lines, but this is easily configurable, making it perfect for quickly checking file headers or starting content.
Example 1: Display the first 10 lines of a file
# Show the default first 10 lines of a log file
head /var/log/dnf.log
Explanation: When used without any options, head reads the specified file and prints its first 10 lines to the terminal.
Example 2: Specify the number of lines to display
# Show the first 5 lines of the hosts file
head -n 5 /etc/hosts
Explanation: The -n option (or just -<number>) allows you to specify exactly how many lines you want to see. This command displays only the first five lines.
Example 3: Display the first few bytes of a file
# Show the first 50 bytes of a binary file
head -c 50 /usr/bin/ls
Explanation: The -c option switches head from line mode to byte mode. This is useful for examining the headers of binary files or data streams.
Example 4: Display headers for multiple files
# Show the first 3 lines of two different configuration files
head -n 3 /etc/ssh/sshd_config /etc/ssh/ssh_config
Explanation: When given multiple filenames, head displays the first few lines of each file. It prints a header (==> filename <==) before the output for each one.
Example 5: Using head with a pipe
# List files by size and show only the top 5 largest
ls -S | head -n 5
Explanation: head is frequently used with pipes to limit the output of other commands. This example first sorts files by size (-S) and then uses head to show only the top five results.
Example 6: Display all but the last few lines
# Display the entire file except for the last 20 lines
head -n -20 data.txt
Explanation: Using a negative number with -n has a special meaning. It instructs head to print all lines from the beginning of the file, stopping a specified number of lines before the end.
Example 7: Quiet mode for multiple files
# Show the first 5 lines of several files without the "==> filename <==" headers
head -q -n 5 *.log
Explanation: The -q (quiet) option is useful when you are processing multiple files but do not want the identifying headers to be printed for each one.