5 Simple Shell Tricks to Empty Files Instantly
This guide shows five practical Linux shell methods—including redirection to /dev/null, using the built‑in ':' or true commands, cat/cp/dd utilities, echo with -n, and the truncate command—to quickly clear a file’s contents without deleting the file itself.
1. Empty file by redirecting to /dev/null
Use shell redirection to null (a non‑existent object) to clear a file’s content.
# > access.log2. Use the built‑in ':' (true) command for redirection
The colon : is a shell built‑in equivalent to the true command; redirect its output to a file to truncate it.
# : > access.log
OR
# true > access.log3. Clear a file with cat/cp/dd using /dev/null
The /dev/null device discards any data written to it, making it ideal for emptying files.
Using cat: # cat /dev/null > access.log Using cp: # cp /dev/null access.log Using dd (where if is input file and of is output file):
# dd if=/dev/null of=access.log4. Empty a file with the echo command
Redirect an empty string or nothing from echo to the file.
# echo "" > access.log
OR
# echo > access.logTo avoid a trailing newline, use the -n flag:
# echo -n "" > access.log5. Use the truncate command
The truncate command resizes a file; with -s 0 it reduces the file to zero bytes, effectively clearing it.
# truncate -s 0 access.logSigned-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.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
