A script to shrink and compress disk images easily
Mar 10, '03 09:30:00AM
Contributed by: carsten
Here is a tcsh shell command which will shrink the unused space of a disk image, then compress it with zlib-level 9.
Features:
- This method usually results in slightly smaller dmg files than just recompressing them. (gzip is not used here, only hdiutil.)
- When you open up the resulting dmg you won't see a huge amount of available space (which looks darn silly on a read-only-compressed disk).
- Filenames with spaces are handled. (Use autocompletion or type a "" before each space in the filename.)
- The original file is retained, with the suffix ".bak" added.
- When finished, an "ls" command is automatically performed showing only the new and original dmg files, so you can compare the exact byte sizes.
- If the Developer Tools "SetFile" command is installed, the type and creator will be set correctly (so the backup file will still have the correct icon and type-association).
Caveats:
- Requires at least 2x free disk space of the image, depending on how much unused space is inside the dmg. (The disk is copied & converted to a read-write dmg, shrunk, then copied & converted again. There doesn't seem to be a way around this without sacrificing the shrinking step.)
- Since this is really a shell alias with autocompletion, it works on one file at a time. (It probably wouldn't be too hard to rewrite this into a script).
- The instructions below are for use with the default tcsh shell. (It shouldn't be too difficult to adapt it for bash.)
[robg adds: I haven't tested this one myself.]
Instructions:
- Add the following lines to ~/Library/init/tcsh/aliases.mine (or create the file if not present):
alias dmgcon 'hdiutil convert -format UDRW \!:1 -o \!:1.UDRW \
&& hdiutil resize -sectors `hdiutil resize \!:1.UDRW.dmg | awk \{print\ \$1\}` \!:1.UDRW.dmg \
&& hdiutil convert -imagekey zlib-level=9 -format UDZO \!:1.UDRW.dmg -o \!:1.UDZO \
&& rm \!:1.UDRW.dmg \
&& mv \!:1 \!:1.bak \
&& mv \!:1.UDZO.dmg \!:1 ;\
[ -f /Developer/Tools/SetFile ] && /Developer/Tools/SetFile -t devr -c ddsk \!:1 ;\
[ -f /Developer/Tools/SetFile ] && /Developer/Tools/SetFile -t devr -c ddsk \!:1.bak ;\
ls -alF \!:1.bak \!:1'
Note: The punctuation and spacing are critical! Also notice that the commands do span multiple lines, this is okay because a "\" is used at the end of each line.
- Add the following lines to ~/Library/init/tcsh/completions.mine (or create the file if not present):
complete dmgcon 'p/*/f:*.{dmg,img}/'
- Open a new terminal window for the changes to become active.
Try it out: "cd" to a directory containing a disk image, then type...
dmgcon [tab]
...to see an autocompleted list of .dmg or .img files. Finish the filename, hit return and watch it go.
Enjoy! You can also search for other hdiutil hints at Mac OS X Hints.
Comments (8)
Mac OS X Hints
http://hints.macworld.com/article.php?story=20030306095219454