Create a disk image from a directory in the Terminal

May 14, '03 09:49:00AM

Contributed by: kirkmc

Apple's Disk Copy program, located in /Application -> Utilities, lets you create a disk image from a folder by drag and drop. You can accomplish the same thing from the command line, but it requires several steps. Here is the procedure to follow; in this example I make a disk image from my Documents directory. First, you need to find out how much disk space the directory holds:

% du -s ~/Documents
65576   /Users/kirk/Documents
The du -s command returns the number of sectors for the directory specified as an argument. This tells you how big the disk image must be. In the above example, there are 65,576 sectors. Add about 5% to this for meta-data: this gives 69,000 rounded up. Now, create the disk image file:
% hdiutil create -sectors 69000 -fs HFS+ -volname Documents ~/Documents
This creates a disk image called Documents in the current working directory. The disk image is formatted in HFS+ and has 69,000 sectors. Next, mount the disk image file:
% hdiutil mount Documents.dmg
Copy the contents of the directory to the disk image. Use ditto and the -rsrcFork option to maintain any resource forks that may exist:
% ditto -rsrcFork ~/Documents /Volumes/Documents
Now that you're finished, you can unmount the disk image:
% hdiutil unmount /Volumes/Documents
It took five commands to create a disk image from a directory. That's a bit more than dragging a folder onto Disk Copy, but it's still pretty quick. And with a little work, you can create a shell script to do this automatically.

Comments (2)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20030512084055685