What is :>filename.txt Doing?

As you have discovered, this just empties the file contents (it truncates the file); that is different from rm as rm would actually remove the file altogether. Additionally, :>file.txt will actually create the file if it didn't already exist.

: is a "do nothing command" that will exit with success and produce no output, so it's simply a short method to empty a file. In most shells, you could simply do >file.txt to get the same result. It also could be marginally faster than other methods such as echo >file.txt as echo could potentially be an external command.

Additionally, echo >file.txt would put a blank line in file.txt where :>file.txt would make the file have no contents whatsoever.


Yes, it's different from rm.

rm would remove the file.

:>filename.txt empties the file, leaving it still there, but zero bytes in size.


The shell invocation of >filename.txt redirects some output to the file "filename.txt" to completelly replace it. So, the shell has to clear all the contents of the given file before writting the output to it.

The output to be redirected is the output of the command executed. Like:

$ echo Hello >filename.txt

Will make the file of name filename.txt to contain exactly (and only) the string Hello.

Executing:

$ echo "New Value" >filename.txt
$ cat filename.txt
New Value

will erase everything inside the file and then write New Value to it.

If the command has no output, like the command true, the file will remain empty (truncated).

$ true >filename.txt
$ cat filename.txt

A command that is also a shell builtin is : (just a double dot (colon)) and that has no output. Being a builtin makes it faster than an external command such as true (which also has no output). So, either:

$ :  >  filename.txt
$ :  >filename.txt
$ :>filename.txt

will remove all content from the file named filename.txt or will create it as an empty file if it doesn't exist.

Is this different from an rm?

That is different than a rm, as a rm will make the file disappear from ls, not make the file to contain 0 bytes.

Does it operate faster or slower than other similar means of zeroing a file or deleting it?

Again, the file is not being deleted (disappear from the list given by ls) it transforms in an empty file (contains 0 bytes).

It should be faster than calling an external command to empty a file. Having to create a child shell to load the executable and exec the command makes external commands slower than the builtin :.

Similar solutions are (some set $? to 1):

[ ]         > filename.txt
builtin     > filename.txt
command     > filename.txt
printf ''   > filename.txt

Tags:

Shell

Bash

Rm