Creating a ram disk on MacOS

I am trying to create a ram disk on MacOS using the following command

diskutil erasevolume HFS+ RAM_Disk_512MB `hdiutil attach -nomount ram://16384`

This seems to work fine on my desktop but when I try to run it on my laptop I get the following error

Unable to find disk for hdiutil attach -nomount ram://16384

Googling hasn't turned up much. Does anyone have an idea what I might be doing wrong or how I might resolve this?

This system that is giving me problems is running MacOS 10.13.6

4

1 Answer

Short answer:

diskutil erasevolume HFS+ RAM_Disk_512MB $(hdiutil attach -nomount ram://16384)

Explanation of the original problem: I'm pretty sure the original problem was due to using the wrong quotes (single-quotes instead of backquotes). Compare these commands:

diskutil erasevolume HFS+ RAM_Disk_512MB `hdiutil attach -nomount ram://16384`
diskutil erasevolume HFS+ RAM_Disk_512MB 'hdiutil attach -nomount ram://16384'

They look really similar, right? But they do very different things; the one with backquotes runs hdiutil ... as a command, and uses its output as an parameter to diskutil. The second treats hdiutil ... as a literal string, and passes that to diskutil, which isn't what you want at all. The two kinds of quotes look very similar (there was at least one book on Unix that used a font where they were identical), so this is an easy (and common) mistake to make.

$( ) does essentially the same thing as backquotes, but is visually and syntactically clearer, so use it instead.

What this actually does: the command hdiutil attach -nomount ram://16384 creates a RAM disk, and prints the path to the device file corresponding to it. Something like "/dev/disk4" (except that it prints it followed by a bunch of spaces). The $( ) then treats that as an argument to the main command, so it runs something like diskutil erasevolume HFS+ RAM_Disk_512MB /dev/disk4, which formats (and implicitly mounts) the newly-created RAM disk.

I'd originally suggested putting double-quotes around the $( ) part, but this turned out to cause trouble. Without double-quotes, the output from the command in $( ) will be parsed by the shell (in a kind of weird way), which usually causes more problems than it helps. In this case, however, the output includes a bunch of spaces at the end, and those can confuse hdiutil if it's told they're part of the device entry's path. The no-quote parsing removes the spaces, so it works that way.

This should be safe from the other things that tend to go wrong with unquoted command expansions, with one big warning: if you have messed with the value of IFS (the shell's "internal field separator") variable, it may do completely weird things.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like