Phase 1Discover the terminal

#3 Creating and reading files

touch, cat, head, tail

Creating files with touch

The touch command creates an empty file. If the file already exists, it simply updates its modification date without changing its content.

Create a file
$ touch file.txt
$ ls
file.txt  notes.txt

Like mkdir, the touch command produces no output when it succeeds. Silence is a good sign in bash!

cat — Display contents

cat (short for concatenate) displays the entire contents of a file in the terminal. It's the simplest way to read a file.

Read a file
$ cat notes.txt
This is a notes file.
Line 2
Line 3

On an empty file, cat displays nothing:

Empty file
$ cat file.txt
$

head — View the beginning

head displays the first lines of a file. By default, it shows the first 10 lines. Very useful for taking a quick look at a large file.

First lines
$ head notes.txt
This is a notes file.
Line 2
Line 3

The -n option lets you choose how many lines to display:

First 2 lines
$ head -n 2 notes.txt
This is a notes file.
Line 2

tail — View the end

tail is the counterpart of head: it displays the last lines of a file. Very handy for checking log files, for example.

Last lines
$ tail notes.txt
This is a notes file.
Line 2
Line 3

With -n 1, you get only the very last line:

Last line only
$ tail -n 1 notes.txt
Line 3

Summary

Here is a recap of the four commands from this lesson:

Summary
touch file.txt   # Create an empty file
cat file.txt     # Display all contents
head file.txt    # Display the beginning
tail file.txt    # Display the end

Your turn

Try the commands touch, cat, head and tail in the terminal below. The file notes.txt contains 3 lines of text for your tests.

terminal — bash
user@stemlegacy:~$