It depends on what exactly the partition is for, and what the purpose of the copy is. However, I will say that in general dd
is an inappropriate tool for backing up filesystems. That's not what it was intended for, either.
It will waste a lot of time copying empty sections of the partition.
It may lead to inconsistencies if the filesystem is currently mounted, in part because it's an OS level entity and may be out of sync with the underlying block device. Calling sync
initially won't help much with this, since the process is not instantaneous.
Use cp -a
or rsync
instead. You then need to create the destination partition, of course, so it is not quite as drop dead easy, but it is much safer and more flexible. If you need to create a filesystem image, see below.
If you are intending to copy the root filesystem, absolutely do not use dd
. You must use something like rsync -ax
(or cp -ax
on individual toplevel directories), because there is a bunch of stuff that must NOT be in the copy. On Linux, this includes:
/dev
/lost+found
/mnt
/proc
/run
/sys
/tmp
Some of these are actually kernel interfaces and not real directories on disk. If you copy them, you are copying a bunch of information that will not apply in the copy; if you try and run a system with it it will just amount to wasted space since the real interface will be mounted on top. Others contain temporary information in use by running processes and those are more of an issue, since the system will not be able to sort out the garbage if you copy that.
If you want to create an image file of the root filesystem (or any filesystem), create an empty image file -- this is an appropriate use for dd
:
dd if=/dev/zero of=whatever.img bs=1024 count=1000000
That's a 1024 MB image (1000000 * 1024). Adjust count
if you want it some other size. Create, e.g., an ext
filesystem in the file:
mke2fs whatever.img
It will warn you this is not a real block device. Proceed. Now mount the image file:
mount whatever.img /mnt/img
/mnt/img
must exist but could anything. You can now rsync
(or cp -a
) into /mnt/img
. The content will remain inside whatever.img
when you unmount it.
However...
Just to be clear, only use the filesystem image method just described if you absolutely need an image file for whatever reason. If your goal is to copy the partition to another hard drive, you don't need an image: create a new partition with an empty filesystem on that drive, mount it, and copy into there. You could instead just put the filesystem content into an empty directory and archive it:
tar -czf myarchive.tar.gz [the directory path]
You can then deploy this in an existing (empty or otherwise) partition by placing it in the toplevel and using:
tar -xzf myarchive.tar.gz
Beware that will overwrite existing files if their paths match something in the archive. It will otherwise leave the existing directory hierarchy the same.