3

is there a command on Linux to remove a file but zeroing it's contents first?

so if i do, something like this:

rm -rf /var/cache/pacman/pkg/*

it would overwrite each file on that directory with 0 values, then erase it

i need it for compacting my VMware image files without creating super big file containing zeros first.

  • Why will a simple delete not do? – terdon Sep 25 '13 at 15:25
  • 2
    Does VMWare not support the trim/discard command? That'd save a bunch of I/O, as you'd not actually need to 0 the sectors. – derobert Sep 25 '13 at 15:26
  • @terdon because the sectors needs to be zeroed first before vmware could compact their image files.. – Kokizzu Sep 25 '13 at 15:29
  • Possibly related: unix.stackexchange.com/questions/63337/… – slm Sep 25 '13 at 16:16
7

The shred command can zero out a file. To do what you want, I think something like this should work

find /var/cache/pacman/pkg -type f -exec shred -n 0 -z {} \; \
    && rm -rf /var/cache/pacman/pkg/*
  • this one works, thanks.. my 1.8G vmdk, now become 1.5G ^^ – Kokizzu Sep 25 '13 at 15:36
5

You can do it with shred command:

shred -z -u <filename>

-z option makes file become zero, then -u option will delete file.

3

You can also use the tool zerofree to zero out all the blocks on disk that are unused. This can save you a significant amount of space.

This method will require that you boot into an alternative OS such as Finnix. You could also use Parted Magic which comes with zerofree installed.

Example

Using Finnix:

$ sudo apt-get update && sudo apt-get install -y zerofree

Once installed you run this tool on the entire partition like so:

$ sudo zerofree -v /dev/sda1

Then poweoff:

$ sudo poweroff

References

  • i wish i could mark "accepted" more than 1 answer.. – Kokizzu Sep 27 '13 at 5:16
  • @Kokizzu - No worries, an upvote is the best compliment! – slm Sep 27 '13 at 5:42
  • ah but the bad part about it, it cannot be executed into a mounted partition.. – Kokizzu Sep 27 '13 at 9:19
  • @Kokizzu - correct, this is an alternative method to shred, but can work on the entire partition, whereas the other methods are essentially per file. – slm Sep 27 '13 at 9:22
  • 1
    Ryan Finnie (the author of Finnix) tells me that Finnix now includes zerofree as of Finnix 107. – Justin Force Dec 9 '13 at 19:16
1

I don't understand when you refer to zeoring.If you want to truncate a file to 0B you can use > filetotruncate.txt. For example:

$ ls -lh file
-rw-r--r-- 1 user user 94M sep 25 17:27 file
$> file && ls -lh file
-rw-r--r-- 1 user user 0 sep 25 17:28 file
  • what i mean with zeroing is overwrite the contents of the file with zeros – Kokizzu Sep 25 '13 at 15:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.