Search code examples
macosxattrhdiutil

Can I modify a disk image while it is open, but not "save changes"?


I have a script where I create a disk image of an SD card using hdiutil and then mount that disk image. I then write extended attributes to the files inside using xattr and important them into a program. Is there any way I can reverse those xattr writes so they don't save when I unmount the image? Ideally I'd keep an untouched copy of the SD card for archive. Is there a way to mount a disk image, make changes to the files inside, then unmount it and those changes aren't "Saved"? I'm trying to avoid copying the SD card twice for time reasons.


Solution

  • You can mount the image with a "shadow" file; changes to the volume will be stored in the shadow file, leaving the original image file unchanged. To reset back to the original state, just eject the image and delete the shadow file.

    Actually, you can be even trickier if you want, by "deleteing" the shadow file while the image is still mounted. The file's directory entry will be deleted immediately, but it remains on disk (& can be read & written) until the last program closes it, which doesn't happen until the image gets ejected. Like this:

    hdiutil mount /path/to/image.dmg -shadow
    rm /path/to/image.dmg.shadow
    

    This way, the changes immediately vanish when the image is ejected; remounting it gets you a clean image. One warning, though: you must fully eject the disk image, not just unmount the volume. Unmounting the volume leaves the image attached to a /dev entry, shadow file changes still in force, etc.

    See the hdiutil man page for details.