Create an APFS RAM disk

apfsdisk-formatdisk-utilitymemory

There are various resources about how to create a RAM disk, but they all deal with HFS+ RAM disks. But how does one create an APFS RAM disk?

I tried passing APFS as file system to the diskutil command like below, but that doesn't work. Since diskutil has a whole bunch of APFS-related subcommands I assume there's more magic necessary.

DISK_ID=`hdiutil attach -nomount ram://$((4 * 1024 * 2048))`
diskutil eraseVolume APFS "RAM Disk" "$DISK_ID"

Best Answer

It works if you create a JHFS+ volume first and convert it to APFS in a second step:

  1. DISK_ID=$(hdiutil attach -nomount ram://$((<number_of_blocks>)))
  2. diskutil eraseDisk JHFS+ "RAM Disk" $DISK_ID
  3. diskutil apfs convert $(tr -d ' '<<<${DISK_ID}s2)

If the RAM disk has a size of 2 GiB (4 * 1024 * 1024)(block_size) or smaller no EFI partition is created and the 3rd command is: diskutil apfs convert $(tr -d ' '<<<${DISK_ID}s1) or more generally:

DISK_ID=$(hdiutil attach -nomount ram://$((<number_of_blocks>)))
SIZE=$(diskutil info $DISK_ID | awk -F'[^0-9]*' '/Disk Size/ {print$4}')
diskutil eraseDisk JHFS+ "RAM Disk" $DISK_ID
if [ $SIZE -le 2147483648 ]; then diskutil apfs convert $(tr -d ' '<<<${DISK_ID}s1); else diskutil apfs convert $(tr -d ' '<<<${DISK_ID}s2); fi

Result:

...
/dev/disk2 (disk image):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:      GUID_partition_scheme                        +4.3 GB     disk2
   1:                        EFI EFI                     209.7 MB   disk2s1
   2:                 Apple_APFS Container disk3         4.0 GB     disk2s2

/dev/disk3 (synthesized):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:      APFS Container Scheme -                      +4.0 GB     disk3
                                 Physical Store disk2s2
   1:                APFS Volume RAM Disk                32.8 KB    disk3s1