Unix & Linux: Empty the contents of a file (3 Solutions!!)

Опубликовано: 16 Июль 2026
на канале: Roel Van de Paar
10
0

👉 https://amzn.to/4aLHbLD 👈 You’re literally one click away from a better setup — grab it now! 🚀👑

As an Amazon Associate I earn from qualifying purchases. Unix & Linux: Empty the contents of a file


The Question: I am aware of three methods to delete all entries from a file.
They are
>filename
touch filename
filename < /dev/null
Of these three I abuse >filename the most as that requires the least number of
keystrokes.
However, I would like to know which is the most efficient of the three (if
there are any more efficient methods) with respect to large log files and small
files.
Also, how does the three codes operate and delete the contents?

Solutions: Please watch the whole video to see all solutions, in order of how many people found them helpful

== This solution helped 309 people ==
Actually, the second form touch filename doesn't delete anything from the file
it only creates an empty file if one did not exist, or updates the last-
modified date of an existing file.
And the third filename < /dev/null tries to run filename with /dev/null as
input.
cp /dev/null filename works.
As for efficient, the most efficient would be truncate -s 0 filename; see here:
http://linux.die.net/man/1/truncate.
Otherwise, cp /dev/null filename or > filename are both fine. They both open
and then close the file, using the truncate-on-open setting. cp also opens /
dev/null, so that makes it marginally slower.
On the other hand, truncate would likely be slower than > filename when run
from a script since running the truncate command requires the system to open
the executable, load it, and the run it.

== This solution helped 45 people ==
Other option could be:
echo -n > filename
From the man page of echo:
-n Do not print the trailing newline character.

With thanks & praise to God, and with thanks to the many people who have made this project possible! | Content (except music & images) licensed under cc by-sa 3.0 | Music: https://www.bensound.com/royalty-free... | Images: https://stocksnap.io/license & others | With thanks to user Mirko Steiner (https://unix.stackexchange.com/users/..., user debal (https://unix.stackexchange.com/users/..., user ash (https://unix.stackexchange.com/users/..., user Arturo Herrero (https://unix.stackexchange.com/users/..., and the Stack Exchange Network (http://unix.stackexchange.com/questio.... Trademarks are property of their respective owners. Disclaimer: All information is provided "AS IS" without warranty of any kind. You are responsible for your own actions. Please contact me if anything is amiss at Roel D.OT VandePaar A.T gmail.com.