Viewing Files
Prerequisites: Working with files and directories
Several commands show a file's contents in different ways.
printf '%s\n' "line 1" "line 2" "line 3" "line 4" "line 5" "line 6" > log.txt
cat log.txt
echo "---"
head -n 2 log.txt
echo "---"
tail -n 2 log.txt
echo "---"
wc -l log.txt
line 1
line 2
line 3
line 4
line 5
line 6
---
line 1
line 2
---
line 5
line 6
---
6 log.txt
catprints the whole file (its name comes from "concatenate" — it can join several files).head -n N/tail -n Nshow the first or last N lines (10 by default).wc -lcounts lines;wc -wwords;wc -cbytes.- (
printf '%s\n' ...printed each argument on its own line to create a sample file — you'll meetprintfagain later.)
Long files: less
less log.txt opens a scrollable viewer: arrow keys or Space to scroll,
/text to search, n for the next match, and q to quit.
Watching a growing file
tail -f app.log keeps showing new lines as they're added — the standard
way to watch a log file live. Press Ctrl + C to stop.
Common mistakes
- Running
caton a huge file floods the terminal. Uselessorhead. - Running
caton a binary file (like an image) prints garbage and can mess up the terminal;resetfixes it.