head: the first lines
head prints the first 10 lines of a file. -n chooses how many:
head numbers.txt
head -n 3 numbers.txtIn the terminal
student@vulntech:~$ head numbers.txt Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8 Line 9 Line 10 student@vulntech:~$ head -n 3 numbers.txt Line 1 Line 2 Line 3
tail: the last lines
tail prints the last 10 lines. It's perfect for logs, where the newest entries are at the end:
tail -n 3 numbers.txt
tail -n 2 logs/web.logIn the terminal
student@vulntech:~$ tail -n 3 numbers.txt Line 198 Line 199 Line 200 student@vulntech:~$ tail -n 2 logs/web.log 2024-06-01 10:59:00 INFO request 119 served 2024-06-01 11:00:00 INFO request 120 served
Following a log with tail -f
tail -f (follow) keeps the file open and prints new lines as they're added. System administrators use it to watch a log while something is happening. Press Ctrl+C to stop:
tail -f /var/log/messagesStarting from a line
tail -n +195 means from line 195 to the end:
tail -n +195 numbers.txtIn the terminal
student@vulntech:~$ tail -n +195 numbers.txt Line 195 Line 196 Line 197 Line 198 Line 199 Line 200
Remember:
head= beginning,tail= end,-n= how many lines,tail -f= keep watching.