Posted on September 12, 2008 at 3:44pm EDT. More.

Creating a RAM disk on Mac OS X

Here is a pair of shell functions to create and destroy a RAM disk on Mac OS X.

# Creates a RAM disk device, formats it as HFS+, then mounts it.
# parameters: size in megabytes
create_ram_disk() {
	RAMDISK_DEVICE=`hdiutil attach -nomount ram://$RAMDISK_SECTORS`
	RAMDISK_PATH=`mktemp -d /tmp/ramdisk.XXXXXX`
	newfs_hfs $RAMDISK_DEVICE # format as HFS+
	df -h $RAMDISK_PATH # report on disk usage

# Destroys the RAM disk created by create_ram_disk # parameters: none destroy_ram_disk() { echo "Destroying $RAMDISK_DEVICE" df -h $RAMDISK_PATH # report on disk usage umount -f $RAMDISK_DEVICE hdiutil detach $RAMDISK_DEVICE rmdir $RAMDISK_PATH }

What are they good for?  I use these in any script that needs to write a lot of files that will be thrown away before the script is over.  For example, I keep the contents of my websites in a subversion repository.  When I want to update the site, I run a script which executes:
  1. create_ram_disk 100 to create a 100MB RAM disk
  2. svn export to write the web files to $RAMDISK_PATH
  3. rsync to copy changed files from the RAM disk to the web host
  4. destroy_ram_disk to clean up
I also do this in release build scripts, telling the xcodebuild command to use a temporary RAM disk for intermediate and product files.  Sure, Mac OS X has an excellent disk cache, but why hassle it when you know that all of those files will be deleted soon anyway?