cp large file to /dev/null to reduce size to zero
You misread the advice, the idea is not to copy the large file to /dev/null
, which wouldn't affect it in any way, outside putting it in cache if space is available.
cp bigfile /dev/null # useless
The advice is not to remove the file then copy /dev/null
to it, as it would keep the original inode unchanged and won't free any disk space as long as processes have that file open.
The advice is to replace the file content with /dev/null
one, which, given the fact /dev/null
size is zero by design, is effectively truncating the file to zero bytes:
cp /dev/null bigfile # works
cat /dev/null > bigfile # works
It might be noted that if you use a shell to run these commands, there is no need to use /dev/null
, a simple empty redirection will have the same effect and would be more efficient, cat /dev/null
being a no-op anyway.
: > bigfile # better
> bigfile # even better if the shell used supports it
Related videos on Youtube
Comments
-
user2393256 almost 2 years
I just came across the advice that if you want to get rid of a large file and a process has the file handle open you should copy it to /dev/null and its size will be reduce to zero.
How does this work? Or does this even work?
After a quick search I found conflicting answers ranging from "Yes, this totally works" to " Your whole machine is going to blow up". Can somebody enlighten me?
I found the question here: https://syedali.net/engineer-interview-questions/
-
Eric Renouf almost 8 yearsWhere did you find the advice? I can't see how doing
cp big_file /dev/null
would modifybig_file
in any way (well, perhaps its atime), and especially not how it would 0 out the file -
user2393256 almost 8 yearsI found it in this blog about potential interview questions: syedali.net/engineer-interview-questions
-
Eric Renouf almost 8 yearsAh, note that you got the direction of copying wrong, that page says "you can ‘cp /dev/null’ on the file" which is the opposite of copying your file to
/dev/null
-
user2393256 almost 8 yearsAh, true i got that wrong. That makes more sense. So nevermind my question and thanks for helping :)
-
-
Gilles 'SO- stop being evil' almost 8 yearsNo,
cp messages /dev/null
cannot possibly truncatemessages
. (Well, sure, it's physically possible, but if a system erases data when told to copy it, it's severely broken.)