Creating, mounting, and dismounting disk images from the command line

Mac OS X Add comments

Every now and then I find something I need to do and, despite my best Google searching, I can’t find clear directions about how to do it. Recently I was writing a shell script in which I needed to create a disk image, mount it, write to it, and dismount it. Apparently nobody who’s done this seemingly simple procedure has bothered to write any of it down, and the man page for hdiutil is pretty thick. But I slogged through it to provide clear, concise instructions for future Googlers.

The command in OS X that manages disk images is hdiutil. The syntax for the command is simple, but there are a lot of options to consider. In this particular example I’m going to create a sparse image that is only as large as the data contained within the image. You can adapt the command to create images to fit your needs.

hdiutil create -size 1g -type SPARSE -fs HFS+ -volname Image ~/Desktop/image

hdiutil The command that manages disk images.

-size 1g Set the size for the disk image. In the case of sparse images, this is the maximum size to which the image can grow. The image file itself will only be as large as the data contained in it. Abbreviations apply, for instance, k for kilobytes, m for megabytes, and g for gigabytes.

-type SPARSE The options for the type of image are SPARSE and UDIF. A sparse image grows with the content, and a UDIF is a set size. UDIF images can be converted to certain subtypes, the explanation of which is beyond the scope of this article.

-fs HFS+
Specifies the filesystem type for the new image. If you’re using this image on a Mac OS X system, you’ll most likely want HFS+.

-volname Image This option sets the name of the volume… the name that shows under the drive on your desktop when it’s mounted.

~/Desktop/image Finally, the location and name of the image you’re creating. In the case of sparse images, the extension .sparseimage will be added to the end. I have created a file named image.sparseimage in my Desktop folder.

After creating the image, you’ll want to mount it, or attach it as a device, so you can write to it.

hdiutil attach ~/Desktop/image.sparseimage

And when you’re done, dismount or detach it.

hdiutil detach /Volumes/Image

Leave a Reply

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in