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.
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.log2. 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.log3. 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.log4. 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.logNote 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
truncateadjusts 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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
