Show the contents of a file with cat, head and tail, then capture output into a file.
Open this lesson in KodokonYou 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.
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 marketOn 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.
head server.log
head -n 5 server.log
tail -n 20 server.log
tail -f server.logBy 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.
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.txtcat command for?> and >>?> appends to the end, >> overwrites the file> overwrites the file, >> appends to the endserver.log?