Occasionally, while dealing with files in a Linux terminal, you may want to clear the content of a file without necessarily opening it using any Linux command line editors. How can this be achieved?
In this article, we will go through several different ways of emptying file content with the help of some useful commands.
With that said, below are means of clearing file content from the command line.
Important: For the purpose of this article, we’ve used the file
access.log in the following examples.
1. Empty File Content by Redirecting to Null
The easiest way to empty or blank a file content using shell redirect
null (non-existent object) to the file as below:
# > access.log
2. Empty File Using ‘true’ Command Redirection
Here we will use a symbol
: is a shell built-in command that is essence equivalent to the
true command and it can be used as a no-op (no operation).
Another method is to redirect the output of
true built-in command to the file like so:
# : > access.log OR # true > access.log
3. Empty File Using cat/cp/dd utilities with /dev/null
In Linux, the
null device is basically utilized for discarding unwanted output streams of a process, or else as a suitable empty file for input streams. This is normally done by a redirection mechanism.
/dev/null device file is therefore a special file that writes off (removes) any input sent to it or its output is the same as that of an empty file.
Additionally, you can empty the contents of a file by redirecting the output of
/dev/null to it (file) as input using the cat command:
# cat /dev/null > access.log
Next, we will use the cp command to blank a file content as shown.
# cp /dev/null access.log
In the following dd command,
if means the input file and
of refers to the output file.
# dd if=/dev/null of=access.log
4. Empty File Using echo Command
Here, you can use an echo command with an empty string and redirect it to the file as follows:
# echo "" > access.log OR # echo > access.log
Note: You should keep in mind that an empty string is not the same as null. A string is already an object much as it may be empty while null simply means the non-existence of an object.
To send a null output to the file, use the flag
-n which tells echo to not output the trailing newline that leads to the empty line produced in the previous command.
# echo -n "" > access.log
5. Empty File Using truncate Command
The truncate command helps to shrink or extend the size of a file to a defined size.
You can employ it with the
-s option that specifies the file size. To empty a file content, use a size of 0 (zero) as in the next command:
# truncate -s 0 access.log
That’s it for now, in this article we have covered multiple methods of clearing or emptying file content using simple command line utilities and shell redirection mechanisms.
These are not probably the only available practical ways of doing this, so you can also tell us about any other methods not mentioned in this guide via the feedback section below.