Operations 4 min read

5 Quick Linux Commands to Empty a File Instantly

Learn five practical Linux techniques—using shell redirection, built‑in commands, /dev/null with cat/cp/dd, echo, and truncate—to clear a file's contents without deleting the file, each with clear examples and explanations.

Liangxu Linux
Liangxu Linux
Liangxu Linux
5 Quick Linux Commands to Empty a File Instantly

This guide explains how to clear the contents of a file in Linux without removing the file itself, presenting five distinct command‑line methods.

1. Redirect to null

Use shell redirection to write nothing into the target file:

# > access.log

2. Use the built‑in : or true command

Both : and true are shell built‑ins that succeed without output. Redirect their output to the file:

# : > access.log
OR
# true > access.log

3. Employ /dev/null with cat , cp , or dd

The special device /dev/null discards any data written to it. Redirect its output to the file using various utilities:

# cat /dev/null > access.log
# cp /dev/null access.log
# dd if=/dev/null of=access.log

4. Use echo with an empty string

Redirect an empty string (or no argument) from echo to the file. Adding -n suppresses the trailing newline:

# echo "" > access.log
OR
# echo > access.log
# echo -n "" > access.log

Note that an empty string differs from null; the former is a zero‑length string, while null represents the absence of an object.

5. Use the truncate command

truncate

adjusts a file’s size. Setting the size to zero clears its contents: # truncate -s 0 access.log These methods provide flexible options for quickly emptying files during system administration or scripting tasks.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

LinuxCATShellFileTRUNCATEEcho
Liangxu Linux
Written by

Liangxu Linux

Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.