Skip to content

Instantly share code, notes, and snippets.

@putnamhill
Last active January 25, 2024 22:16
Show Gist options
  • Save putnamhill/5aeeeeb273eb57f4ce7b39b49a28a376 to your computer and use it in GitHub Desktop.
Save putnamhill/5aeeeeb273eb57f4ce7b39b49a28a376 to your computer and use it in GitHub Desktop.
Steps to attach a dmg disk image using hdiutil while capturing the mount point and dev entry for detaching when done
#!/bin/bash
dmg_path="$1"
# use process redirection to capture the mount point and dev entry
IFS=$'\n' read -rd '\n' mount_point dev_entry < <(
# mount the diskimage (leave out -readonly if making changes to the file system)
hdiutil attach -readonly -plist "$dmg_path" | \
# convert output plist to json
plutil -convert json - -o - | \
# extract mount point and dev entry
jq --raw-output '
.[] | .[] |
select(."volume-kind" == "hfs") |
."mount-point" + "\n" + ."dev-entry"
'
)
# work with the file system
echo "ls $mount_point:"
ls "$mount_point"
# unmount the disk image (use the -force option if necessary)
hdiutil detach "$dev_entry"
@moisoto
Copy link

moisoto commented Jan 21, 2021

Thanks a lot for this!!!
This was very helpful, since jq is not installed by default on a Mac, I made some modifications that also simplifies the process a little:

#!/bin/bash

dmg_path="$1"
IFS=$'\n' read -d'\n' dev_entry mount_point < <(
        hdiutil attach -readonly "${dmg_path}.dmg" | grep $dmg_path | awk '{print $1; print $3}'
)

# work with the file system
echo "ls -l $mount_point:"
ls -l "$mount_point"

# unmount the disk image (use the -force option if necessary)
hdiutil detach "$dev_entry"

Also: Please notice that this in this version you should omit the .dmg on the parameter for the script

@jchin-ria
Copy link

This script is good BUT the "mount_point" does not take into account anything that can contain a space.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment