Four Ways to Quickly Create Files from Command Line on Unix-Like Systems (bash)

Quickly creating files in Unix-like systems from command line is pretty easy. Here are four ways to do it.

Method 1: touch filename

Just use the touch command followed by the filename:

[ahmed@amayem ~] touch filename
[ahmed@amayem ~] ls
filename

Method 2: > filename

This is probably the easiest way:

[ahmed@amayem ~] ls
[ahmed@amayem ~] > filename
[ahmed@amayem ~] ls
filename

Explanation

The man bash page gives us the explanation:

Redirecting Output
    Redirection of output causes the file whose name results from the expansion of word to be opened for writing on file descriptor n, or the standard output (file descriptor 1) if n is not specified. If the file does not exist it is created; if it does exist it is truncated to zero size.

    The general format for redirecting output is:

        [n]>word

The important part here is the following: If the file does not exist it is created;

Corollary Method (Any Command) > filename

Since > in this context stands for redirection, we can redirect the output of any command, for example the ls command:

[ahmed@amayem ~] ls
[ahmed@amayem ~] ls > filename
[ahmed@amayem ~] ls
filename

Method 3: >> filename

This way uses one extra character:

[ahmed@amayem ~] ls
[ahmed@amayem ~] >> filename
[ahmed@amayem ~] ls
filename

Explanation

Much like the previous method the man bash page gives us more detail

Appending Redirected Output
    Redirection of output in this fashion causes the file whose name results from the expansion of word to be opened for appending on file descriptor n, or the standard output (file descriptor 1) if n is not specified. If the file does not exist it is created.

    The general format for appending output is:

        [n]>>word

Corollary Method (Any Command) >> filename

Since >> in this context stands for redirection (by appending), we can redirect the output of any command, for example the ls command:

[ahmed@amayem ~] ls
[ahmed@amayem ~] ls >> filename
[ahmed@amayem ~] ls
filename

Method 4: Command Line File Editors

You will have to check which command line file editor you have on your system and how it’s done.

vi vim ex view rvim rview

Though the executable may be the same vim acts differently depending on the name of the command. I will just cover vi in this example.

[ahmed@amayem ~] ls
[ahmed@amayem ~] vi filename

Here we have to input something, otherise vi won’t make the file. So enter insert mode by pressing i, input something, then exit insert mode using Esc or ctrl+c, then save using :q. Let’s check again:

[ahmed@amayem ~] ls
filename

References

  1. man bash page

Ahmed Amayem has written 90 articles

A Web Application Developer Entrepreneur.