Viewing files
You'll often need to look inside files: config files, logs, data and code. The terminal has a tool for every situation, from tiny files to logs with millions of lines.
cat: print a whole file
cat(short for concatenate) prints files. With several files, it joins them.-nadds line numbers.- It's best for short files. A huge file would flood your screen.
head and tail: the start and the end
| Command | Shows |
|---|---|
head file |
The first 10 lines |
head -n 3 file |
The first 3 lines |
tail file |
The last 10 lines |
tail -n +2 file |
Everything from line 2 onwards (handy for skipping a CSV header) |
tail -f file |
Follow a file live as new lines are added, which is perfect for watching logs. Ctrl + C to stop. |
tail -f /var/log/app.logis one of the most-used commands on servers: you watch errors appear in real time while you reproduce a bug.
less: scroll through big files
On a real machine, less bigfile.log opens a scrollable viewer:
| Key | Action |
|---|---|
| Space / b | Page down / up |
| ↑ ↓ | Line by line |
/word |
Search forward for "word" (n = next match) |
G / g |
Jump to the end / start |
q |
Quit |
(The simulator just prints the file for less.)
wc: count lines, words and characters
wc -l (count lines) is everywhere: "how many users are in this file?", "how many errors today?"
File sizes and disk usage
ls -lhshows each file's size in human units.du -sh foldershows a folder's total size.df -h(on real machines) shows how full your disks are.
Editing files in the terminal
Sooner or later you'll need to edit a file on a server with no GUI:
| Editor | Difficulty | Quick survival guide |
|---|---|---|
| nano | Easy | Edit normally. Ctrl + O saves, Ctrl + X exits. The shortcuts are shown at the bottom. |
| vim | Steep curve, very powerful | Press i to type. Press Esc, then :wq + Enter to save and quit, or :q! to quit without saving. |
| code | VS Code | code . opens the current folder in VS Code (if it's installed) |
The simulator has no editors, but you can create and change files with echo:
> replaces a file's contents, and >> appends to it. More in the Pipes lesson.
Practice
- How many lines are in
data/app.log? - Show only the header (first line) of
data/sales.csv. - Show the last 3 entries of the log.
- Show
Documents/todo.txtwith line numbers.
1.Which command shows the last 20 lines of a log file?
2.What does tail -f app.log do?