Kodokon kodokon.com

Reading a file and redirecting output

Show the contents of a file with cat, head and tail, then capture output into a file.

7 min · 3 questions

Open this lesson in Kodokon

You do not always need to open an editor just to glance at a file. The cat command prints its contents straight into the terminal. Its name comes from concatenate, "to join end to end", because it can also display several files one after another. It is the ideal tool for small files: a few dozen lines at most.

BASH
yoann@laptop:~/my-project$ cat shopping.txt
Bread
Cheese
Tomatoes

yoann@laptop:~/my-project$ cat shopping.txt notes.txt
Bread
Cheese
Tomatoes
Do not forget the Saturday market
cat on one file, then on two files shown one after the other.

On a file of ten thousand lines, cat scrolls the screen for ten seconds and you only get to see the end. Two more precise commands exist: head shows the beginning of a file, tail shows the end. Both show 10 lines by default, and the -n option lets you choose how many. tail has a superpower with the -f option (follow): it stays open and prints new lines as they arrive. That is how you watch a server log live.

BASH
head server.log
head -n 5 server.log
tail -n 20 server.log
tail -f server.log
The beginning, the first 5 lines, the last 20, then the end live (Ctrl + C to quit).

By default a command writes its result to the screen. But you can divert that result into a file, the way you would divert water from a hose into a bucket. This is redirection, and it is written with an angle bracket. A single angle bracket > sends the output into a file, overwriting whatever it contained. A double angle bracket >> appends to the end without erasing anything. That one-character difference changes everything. To check what you have just produced without printing all of it, the wc command (word count) with the -l option (lines) counts the number of lines in a file.

BASH
yoann@laptop:~/my-project$ echo "My first line" > notes.txt
yoann@laptop:~/my-project$ echo "My second line" >> notes.txt
yoann@laptop:~/my-project$ cat notes.txt
My first line
My second line
yoann@laptop:~/my-project$ ls -l > inventory.txt
yoann@laptop:~/my-project$ wc -l inventory.txt
7 inventory.txt
Create a file, append a line, check it, capture some output then count its lines.

Knowledge check

Make sure you remember the key points of this lesson.

  1. What is the cat command for?
    • Showing the contents of a file in the terminal
    • Creating an empty file
    • Deleting a file
    • Counting the lines in a file
  2. What is the difference between > and >>?
    • > appends to the end, >> overwrites the file
    • > overwrites the file, >> appends to the end
    • None, both write into a file
  3. How do you show the last 20 lines of the file server.log?
    • head -n 20 server.log
    • cat -n 20 server.log
    • tail -n 20 server.log