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() {
local RAMDISK_SIZE_MB=$1
local RAMDISK_SECTORS=$((2048 * $RAMDISK_SIZE_MB))
RAMDISK_DEVICE=`hdiutil attach -nomount ram://$RAMDISK_SECTORS`
RAMDISK_PATH=`mktemp -d /tmp/ramdisk.XXXXXX`
newfs_hfs $RAMDISK_DEVICE # format as HFS+
mount -t hfs $RAMDISK_DEVICE $RAMDISK_PATH
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:
- create_ram_disk 100 to create a 100MB RAM disk
- svn export to write the web files to $RAMDISK_PATH
- rsync to copy changed files from the RAM disk to the web host
- destroy_ram_disk to clean up