Terminal 101: Creating and Mounting DMG Files
Posted 04/30/2012 at 11:34am
| by Cory Bohon

Every Monday, we'll show you how to do something new and simple with Apple's built-in command line application. You don't need any fancy software, or a knowledge of coding to do any of these. All you need is a keyboard to type 'em out!
Disk Utility is a great way to create, burn, and otherwise manage disk image files on your Mac. And interestingly enough, you can do the same in Terminal with the hdiutil program. It’s quicker than dealing with Disk Utility and it's more customizable.
What is a DMG File?
DMG files are an alternative to zip files, and make up the basic binary structure of a physical disk, but in virtual form. OS X treats these disk images just as it would a CD, DVD, or external hard drive, allowing you to store files inside and share the .dmg file with someone.
Creating a DMG File
DMG files can be created in Terminal by issuing the following one-line command:
hdiutil create -megabytes x -fs HFS+ -volname y ~/Desktop/y
In the above command, replace x with a number representing how large the DMG file should be (in megabytes). Replace both instances of y with the name of the DMG file. You're welcome to choose a different path other than the Desktop to save the DMG, but it’s often the most convenient location.

So, if we wanted to create a 5 megabyte disk image called “maclife,” we’d issue the following command:
hdiutil create -megabytes 5 -fs HFS+ -volname maclife ~/Desktop/maclife
After a few seconds, you’ll see the file appear on your Desktop. At this point, you can add files to the disk through the Finder if you desire.

Mounting a DMG File

You can mount the DMG file in the finder easily by issuing the following command:
open disk.dmg
Where “disk.dmg” is the path and name of your saved DMG file. Once the file is mounted, you’ll be able to see and access its contents by navigating to:
cd /Volumes/volumename
Replace volumename with the name that you specified when creating the DMG file. You'll see your disk image show up, and you can navigate into the volume using the cd command. Placing files in the disk image is as easy as using the aforementioned mv or cp commands.
Ejecting a DMG File

Unlike zip files, DMG files need to be ejected when you’re done with them. To eject a DMG file, use the following hdiutil command:
hdiutil detach /Volumes/volumename
Replace volumename with the name of the disk volume. When you press enter, the disk will be unmounted from the system. You can optionally click the eject button in the Finder, or drag the mounted image from the Desktop to the Trash in the Dock (which will turn into an eject icon).
Cory Bohon is a freelance technology writer, indie Mac and iOS developer, and amateur photographer. Follow this article's author, Cory Bohon on Twitter.