#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.
$ touch file.txt
$ ls
file.txt notes.txtLike 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.
$ cat notes.txt
This is a notes file.
Line 2
Line 3On an empty file, cat displays nothing:
$ 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.
$ head notes.txt
This is a notes file.
Line 2
Line 3The -n option lets you choose how many lines to display:
$ head -n 2 notes.txt
This is a notes file.
Line 2tail — 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.
$ tail notes.txt
This is a notes file.
Line 2
Line 3With -n 1, you get only the very last line:
$ tail -n 1 notes.txt
Line 3Summary
Here is a recap of the four commands from this lesson:
touch file.txt # Create an empty file
cat file.txt # Display all contents
head file.txt # Display the beginning
tail file.txt # Display the endYour 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.