Creating a ramdisk in macOS

By Jännät (@jaennaet.fi)
Published:

TL;DR: this script can be used to create APFS ramdisks. Eg. create-ramdisk.sh 2048 would greate a 2048MiB / 2GiB ramdisk with the default volume name ramdisk.

Uses for ramdisks

Ramdisks are extremely fast, so they're handy for eg. scratch space and temporary storage for anything that doesn't have to survive a reboot. I use one as a download directory (depending on the size of the download of course), and only rarely move downloads to permanent storage.

How do

It's not a widely known feature, but hdiutil supports creating RAM-backed block devices:

hdiutil attach -nomount ram://${RAMDISK_SECTORS}

-nomount is required because the created block device won't have a file system (yet), and ${RAMDISK_SECTORS} is the number of 512-byte sectors to reserve for the device.

As an example, to create a 100MiB (note that it's mebibytes and not megabytes) device, we'd want a device with 2048 * 100 = 204800 sectors:

❯ hdiutil attach -nomount ram://204800
/dev/disk8

diskutil list will show the device as a disk image:

❯ diskutil list

/dev/disk0 (internal, physical):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:      GUID_partition_scheme                        *1.0 TB     disk0
   1:             Apple_APFS_ISC Container disk1         524.3 MB   disk0s1

[… snip …]

/dev/disk8 (disk image):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                                                   +104.9 MB   disk8

We can now use /dev/disk8 like any block device. We can now use diskutil to create an APFS volume on it. Let's call the volume simply "ramdisk":

❯ diskutil apfs create /dev/disk8 ramdisk
Started APFS operation on disk8
Creating a new empty APFS Container
[…]

And there we go: diskutil automatically mounts the created volume, so we now have a 2GiB volume under /Volumes/ramdisk that shows up like any removable disk in Finder:

Ejecting it will destroy the backing block device as well.

I've packaged all this up into a simple script that takes a size in MiB and an optional volume name and creates an APFS ramdisk volume.