How can I get the path to a disk image from its disk identifier?

Say that I have a disk image named MyDiskImage.dmg with a mountable volume named MyVolume whose disk identifier is disk7s2. I can get the disk identifier of the volume from the path to the disk image by parsing the output of the shell command hdiutil attach /path/to/MyDiskImage.dmg:

do shell script "hdiutil attach /path/to/MyDiskImage.dmg | egrep '/Volumes/MyVolume' | egrep -o 'disk[0-9]+s[0-9]+'" --> "disk7s2"

How can I do the reverse, i.e., get the path to the disk image knowing the disk identifier of its mountable volume? I’ve searched extensively, including the man pages for hdiutil, diskutil, fdisk, df, and a few others, but have had no success. Any help is much appreciated.

Model: MacBook Pro
Browser: Safari 536.30.1
Operating System: Mac OS X (10.8)


you can get the information with

do shell script "diskutil info /dev/disk7s2 | awk '/Mount Point/'"

my egrep/sed knowledge is quite poor, you have to extract the last part of the line

Thank you for the suggestion. I had looked at diskutil info. Unfortunately, the mount point that is extractable from diskutil info /dev/disk7s2 is the path to the mounted volume of the disk image, i.e., /Volumes/MyVolume, not the path to the disk image itself. It’s the latter that I’m trying to get.

hdiutil info

prints out the information about all attached images, it might be easier to parse the result in plist format

hdiutil info -plist

That the answer!! The output from hdiutil info contains both the disk identifier and the path to the disk image for every attached disk image. It won’t be a problem putting together a parsing solution. I don’t have time at the moment but will submit it later. Thank you, Stefan, for that great solution.

Here is a sed solution:

on getDiskImageFromDiskIdentifier(diskIdentifier)
	tell (paragraphs of (do shell script "hdiutil info | sed -En 's/^[" & space & tab & "]*image-path[^/]+(.+)$/\\1/p;s/^[" & space & tab & "]*[/]dev[/](" & diskIdentifier & ")[" & space & tab & "].+$/\\1/p;'")) to repeat with i from length to 1 by -1
		if item i = diskIdentifier then
			set diskImagePosixPath to item (i - 1)
			exit repeat
		end if
	end repeat
	return diskImagePosixPath
end getDiskImageFromDiskIdentifier

-- Extract the disk image path from the disk image's disk identifier
getDiskImageFromDiskIdentifier("disk7") --> "/path/to/MyDiskImage.dmg"

-- Extract the disk image path from the volume's disk identifier
getDiskImageFromDiskIdentifier("disk7s2") --> "/path/to/MyDiskImage.dmg"

Here’s a seddier one:

on getDiskImageFromDiskIdentifier(diskIdentifier)
	return (do shell script ("hdiutil info | sed -En '/^image-path/ h ; /^[/]dev[/]" & diskIdentifier & "/ { g ; s/^[^/]+//p ; q ; }'"))
end getDiskImageFromDiskIdentifier


Wow, that is a beautiful sed script.

P.S. Does not sed have the highest ratio of (powerful capabilities) / (utilization of those capabilities) in the computer universe? :slight_smile: