5 Methods to Clear File Contents in Linux

  1. Using Standard Redirection

The most straightforward way to empty a file is by using the shell redirection operator > without a preceding command. This truncates the file to zero length immediately.

> server.log

  1. Using the Colon or True Command

The : (colon) is a shell built-in command that does nothing and returns a success status (it is synonymous with the true command). Redirecting the output of these commands to a file is a common technique to clear its contents without deleting the file itself.

: > server.log
# Alternatively
true > server.log

  1. Using /dev/null with File Utilities

In Linux, /dev/null is a special device file that discards all data written to it and provides an End of File (EOF) when read. You can use standard utilities like cat, cp, or dd to read from this null device and overwrite the target file.

Using cat:

cat /dev/null > server.log

Using cp to copy the null device content:

cp /dev/null server.log

Using dd for low-level copying:

dd if=/dev/null of=server.log

  1. Using the Echo Commmand

You can redirect an empty string into a file using echo. Its important to note that an empty string is not the same as null; using echo "" typically writes a newline character to the file, resulting in a file size of 1 byte. To ensure the file is completely empty (0 bytes), use the -n flag to suppress the trailing newline.

# Writes a newline character (1 byte)
echo "" > server.log

# Completely empties the file (0 bytes)
echo -n "" > server.log

  1. Using the Truncate Command

The truncate command is used to shrink or extend the size of a file to a specified dimension. By setting the size to 0 with the -s flag, you can effectively wipe all data from the file.

truncate -s 0 server.log

Tags: Linux Shell System Administration File Management Command Line

Posted on Sun, 17 May 2026 19:53:20 +0000 by TheMoose