Harness the Combinatoric Power of Command-Line Tools and Utilities

../Videos

Three Ways to Create Files

Commands Bash

Published January 21, 2019

Explore three ways to create files using the CLI

Transcript

Hi everyone, this is Brian and today we’re going to look at three ways to create files.

The first way to create files is with the touch command. Usually, you use touch to update the timestamp on a file. But if the file doesn’t exist, touch creates a blank one.

Let’s create three files with the touch command:

touch one.txt two.txt three.txt

This one command creates three files. You can specify as many files as you’d like.

Now list the contents of the directory and you’ll see the files:

ls
one.txt two.txt three.txt

These files are empty, but you can edit them in your favorite editor.

The second way to create files is with the echo command and shell redirection. Here’s how:

echo "Hello there." > four.txt

The text “Hello there.” is redirected into that file instead of being printed to the screen. Look at the file’s contents with cat:

cat four.txt
Hello there.

A single arrow always replaces the file content. To add another line, use two arrows:

echo "This is another line." >> four.txt

You can keep appending text to the file this way.

You can save the output of any program that prints to the screen. For example, save the output of the directory listing to the file ’list.txt'

ls > list.txt

Instead of seeing the directory listing on the screen, it’s in the file.

cat list.txt

The third way to create files is to use cat and a here-document. We’ll tell the cat command to accept a here-document and read in all of the text that follows until it finds the line EOF. Then we’ll tell it to save the result to the file five.txt:

cat << 'EOF' > five.txt
This is a line
So is this.
This is line 3
EOF

The file saves. We can use cat to look at the file contents:

cat five.txt
This is a line
So is this.
This is line 3

There you have it. Three methods to create files. Practice with these and see if you can figure out which method works for you.