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.

derobert
  • 109,670
Kokizzu
  • 9,699
  • 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: http://unix.stackexchange.com/questions/63337/how-can-i-be-sure-that-a-directory-or-file-is-actually-deleted/63343#63343 – slm Sep 25 '13 at 16:16

4 Answers4

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/*
slm
  • 369,824
5

You can do it with shred command:

shred -z -u <filename>

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

cuonglm
  • 153,898
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

slm
  • 369,824
  • i wish i could mark "accepted" more than 1 answer.. – Kokizzu Sep 27 '13 at 05:16
  • @Kokizzu - No worries, an upvote is the best compliment! – slm Sep 27 '13 at 05:42
  • ah but the bad part about it, it cannot be executed into a mounted partition.. – Kokizzu Sep 27 '13 at 09: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 09:22
  • 1
    Ryan Finnie (the author of Finnix) tells me that Finnix now includes zerofree as of Finnix 107. – Justin Force Dec 09 '13 at 19:16
  • http://unix.stackexchange.com/questions/44234/clear-unused-space-with-zeros-ext3-ext4 also covers this topic (for ext3/4 filesystems). – Anon Mar 25 '16 at 12:53
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
terdon
  • 242,166