Linux Command Line Basics
Reading and Searching Files
Reading files is a constant task. Here are the commands you will reach for every day.
Quick look with cat
cat prints a file's entire contents:
cat /etc/hostname
Large files with less
For anything longer than a screen, use less. It lets you scroll and search:
less /var/log/syslog
| Key | Action |
|---|---|
Space / PgDn |
Scroll down |
b / PgUp |
Scroll up |
/ |
Search forward, then n for next match |
q |
Quit |
`cat` vs `less`
Use cat for short files and less for anything long. less is safe even on enormous files because it only reads what you view.
Just the top or bottom with head and tail
head -20 access.log # first 20 lines
tail -20 access.log # last 20 lines
tail -f access.log # follow new lines as they are written
tail -f is invaluable for watching live logs. Press Ctrl + C to stop.
Never `cat` a log
Logs can be thousands of lines. cat /var/log/syslog floods your screen — use less or tail instead.
Searching with grep
grep searches files for a pattern:
grep "error" /var/log/syslog # every line containing "error"
grep -i "error" log.txt # ignore case
grep -n "error" log.txt # show line numbers
grep -r "TODO" ~/projects # search an entire directory
Piping: the glue of the shell
The pipe symbol | takes the output of one command and feeds it into another:
ls -la | grep "jan" # only files modified in January
grep "error" log.txt | head -20 # first 20 matching lines
Try it
grep -i "root" /etc/passwd— find lines mentioning rootls -la / | head— first ten entries of the root directorytail -n 5 /etc/passwd— the last five lines
Advertisement