AFP548

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

Recently I was writing a shell script in which I needed to create a disk image, mount it, write to it, and dismount it. The command in OS X that manages disk images at the command line is hdiutil, and the man page is rather long. 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.

Read on for more…

The basic command looks like this:

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

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.

<code>hdiutil attach ~/Desktop/image.sparseimage</code>

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

<code>hdiutil detach /Volumes/Image</code>
Exit mobile version