Wednesday, April 7, 2010

/proc/self/fd/0

cat somefile | cp /proc/self/fd/0 someotherfile

I never knew this was possible!

Now you might ask yourself what this is good for but just the other day I was wondering how I could turn a copy of a drive partition made with dd into a sparse file. For example this copies the entire first partition of your first disk to a file:

dd if=/dev/sda1 of=partition.backup

Of course, depending on the size of the partition this file can get quite large. But knowing that most of the time a disk contains a large number of empty blocks and at the same time Linux supports sparse files wouldn't it be great if the file would only contain the blocks that actually have any data in them?

Now, the dd command doesn't support sparse files, but cp does have a --sparse=always option. So you could just use that to make a sparse copy of the file. But then you would have two copies of a potentially very large file on your system, which you might not have room for.

So I had been wondering if there was a way to pipe the output of dd to the input of cp. For dd this is simple because by default it writes it's output to the standard output if you don't give it an output file name, but cp does no tsupport reading from the standard input... until I found the above option on the ntfsclone man page. Cool stuff!

PS: Quite often free blocks on a drive aren't actually empty, but might still be filled with old data that used to be stored there. In those cases it doesn't help trying to make a sparse copy. To remedy that situation you can use zerofree before making the copy of the partition.

No comments:

Post a Comment