Course outline · 0% complete

0/29 lessons0%

Course overview →

Reading files: cat, less, head, tail

lesson 3-1 · ~10 min · 7/29

Quiz

Warm-up from lesson 2-3: what does `touch report.txt` do when report.txt does not exist yet?

Putting text in, getting text out

Reading files without opening an editor is the daily bread of server work: a deploy fails, and the answer is inside a log file on a machine with no desktop. These tools let you inspect any file — a peek at the top, the newest lines at the bottom, or a full scroll — straight from the prompt.

To have something to read, we need files with content. The quickest way: echo "text" > file.txt saves echo's output into a file instead of printing it. The > arrow is redirection, and >> appends to the end instead of overwriting. Unit 5 covers both deeply. For now, just use them as a file-filling trick.

Reading tools, smallest to largest:

  • cat file: print the whole file at once (short for concatenate, it can print several files back to back).
  • head -n 5 file: just the first 5 lines.
  • tail -n 5 file: just the last 5 lines. Perfect for checking the newest entries of a log.
  • less file: open the file in a scrollable reader for anything long. Same keys as man from lesson 1-3: space to page down, q to quit.

Code exercise · bash

Run it. Three echo lines build a shopping list (note > for the first line, >> to append the rest), then cat prints the whole file.

Code exercise · bash

One more cat flag worth knowing: `-n` numbers each output line. When an error message says "line 2", this is how you look up line 2 without counting by hand. Run it.

Code exercise · bash

head and tail on a bigger file. `seq 1 100` prints the numbers 1 to 100, and we save them all into numbers.txt.

Quiz

A server log has 2 million lines and you want to see the most recent errors at the end. Which command fits best?

Code exercise · bash

Your turn. Save the numbers 10 through 20 into `range.txt` using seq and >, then print its first 2 lines and its last 1 line. Expected output: ``` 10 11 20 ```