Opening every file in a full editor just to check its contents or find one line is slow and often impractical on a remote server with no GUI editor at all. cat, less, head, tail, and grep are the fast, purpose-built tools for exactly this.
Beginner
2 min read
cat: dump a whole file to the screen
cat (concatenate) prints a file's entire contents directly to the
terminal — ideal for short files, impractical for anything long enough to
scroll past the visible screen:
$ cat config.txtsetting_one=truesetting_two=false
less: view a long file, one screen at a time
less opens a file for scrollable viewing without loading the whole thing
into an editor — space bar or arrow keys to scroll, /searchterm to search
within the file, q to quit:
$ less server.log
less is specifically useful for files too long to usefully cat — a
multi-megabyte log file dumped with cat scrolls past faster than anyone
could read it; less lets you navigate and search it properly.
head and tail: just the beginning or end
head shows the first lines of a file (10 by default); tail shows
the last lines — both useful when you specifically want the start or end of a
long file rather than the whole thing:
$ head -n 5 access.log # first 5 lines$ tail -n 20 access.log # last 20 lines$ tail -f access.log # -f (follow): keep showing new lines as they're written
tail -f is a genuinely essential habit for watching a live log file in real
time as a server actively writes to it — directly useful when debugging a
running system, connecting to this domain's later lesson on processes.
grep: search for a pattern, across one file or many
grep searches text for lines matching a pattern — one of the most-used
command-line tools in practice, for finding a specific error message across a
huge log, or a specific function name across an entire codebase:
$ grep "error" server.log # lines containing "error"$ grep -i "error" server.log # -i: case-insensitive$ grep -r "TODO" src/ # -r: recursively search every file in a directory$ grep -n "error" server.log # -n: show line numbers too
Combining these tools instead of learning one giant command
None of these tools try to do everything — grep searches, less views,
tail shows recent lines. The next lesson (pipes and redirection) covers
exactly how these small, focused tools combine into more powerful combined
commands — tail -f access.log | grep "error" (watch a live log, but only
show lines containing "error") does something none of the individual tools do
alone, built entirely from tools that each do one simple thing well.