Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!

An AppleScript to mount, run, unmount a disk image Apps
A number of hints (and newsgroup postings elsewhere) have addressed the problem of creating a script that mounts a disk image, runs an application that uses data from the image, and then unmounts the image after the application quits. By far the best was one was in a comment from Puffyn in a thread here last year, but it never quite worked on my system.

The problem I kept having was that the script would work perfectly the first time I ran it, but the second and all later times (until a reboot), the script would mount the disk image and launch the application that uses the image -- but the application would not detect the image, and ask me to mount it. The application was a Classic app (OED2 CD-ROM), which may or may not have had something to do with it. OED2 CD-ROM is the Oxford English Dictionary software, and its data needs to be on a CD-ROM or disk image, apparently.

Under Panther (or maybe under OS X in general), it seems that it's not easy for a script to unmount a disk so cleanly that it can be mounted a second time in a way that all applications can see it. I found that the script needs to unmount the disk (apparently with a "force" switch for the cleanest possible rsult) AND detach the corresponding device (disk1, etc.) in OS X's list of devices.

Anyway, with the help of many people on the forums (notably Dale Mox and jbc), I finally put together a script that seems to work perfectly, at least on my system. The last problem that needed solving was determining the name of the device on the fly, because the disk number of the image will be different at different times, depending on whether or not you've mounted USB or Firewire disks, etc. Dale Mox solved that one for me.

Here's the code. It will need to be customized to run on your system, but all the changes that need to be made are in the declarations at the top. Here are the explanations of the variables:
  • diskname: should be the name you see under the icon for the disk image on your desktop.
  • diskpath: should be the full path to the disk image file on your hard disk. Get this by selecting the file, press Command-I for Get Information, and combine the "Where" string with the "Name and extension" string.
  • itemname: should be the full path of the application program that the script should run.
  • appname: should be the name of the application itself (without the path).
As I said, this works here, but I'll be grateful for fixes and improvements.
property diskname : "OED2"
property diskpath : "Macintosh HD:Applications (Mac OS 9):OED2 program:OED2.dmg"
property itemname : "Macintosh HD:Applications (Mac OS 9):OED2 program:OED2 CD-ROM"
property appname : "OED2 CD-ROM"

on run
  tell application "Finder"
    if not (exists the disk diskname) then
      do shell script ("hdiutil attach " & quoted form of 
        POSIX path of (diskpath as string) & " -mount required")
      repeat until name of every disk contains diskname
        delay 1
      end repeat
    end if
    open item itemname
  end tell
  delay 5
end run
-- remainder based on hint by puffyn at macosxhints.com:
-- hint named "Quick Applescript to Mount Disk Image"
-- shell script to get devname by Dale Mox with fixes by jbc 
on idle
  set devname to do shell script "mount | grep " & diskname & 
    " | cut -f1-1 -d \" \" | cut -f3-3 -d \"/\""
  tell application "Finder"
    if not (exists the disk diskname) then
      return
    else
      set x to the name of every process
      if appname is not in x then
        do shell script ("hdiutil unmount /Volumes/" & diskname & " -force")
        do shell script ("hdiutil detach " & devname & " -force")
        tell me to quit
      end if
    end if
  end tell
  return 2
end idle
Thanks in advance for any improvements.
    •    
  • Currently 2.33 / 5
  • 1
  • 2
  • 3
  • 4
  • 5
  (3 votes cast)
 
[61,787 views]  

An AppleScript to mount, run, unmount a disk image | 20 comments | Create New Account
Click here to return to the 'An AppleScript to mount, run, unmount a disk image' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
An AppleScript to mount, run, unmount a disk image
Authored by: Dale Mox on Sep 07, '04 11:25:22AM
hehe, *proud* (of the very little I did to make to whole thing function)
By the way, is the
do shell script ("hdiutil unmount /Volumes/" & diskname & " -force")
necessay? I would think a simple
do shell script ("hdiutil detach " & devname)
with or without the -force, should be able to unmount and detach the whole disk.
However, I stand by 'If it ain't broke, don't fix it" (unless it hogs the CPU while functioning)
Dale Mox

[ Reply to This | # ]
An AppleScript to mount, run, unmount a disk image
Authored by: emendelson on Sep 07, '04 02:13:06PM

What Dale says (and thanks again, Dale!) *should* be right, but OS X seems to have some obscure bugs that prevent it from doing the right thing every time it should.

If I remove the line that Dale mentioned, the script works two or three time - but then, the next time, it launches the application, and the application complains that the disk image is not available - even though it's right there on the desktop. And then the script won't work again (I mean the application won't see the disk image again) until a reboot.

When I include the unmount AND the detach lines, the script continues to work correctly even when I run it ten times - which is the most I've tried so far.

As Dale says, the script is a bit of a CPU hog when it's unmounting and detaching, but this is probably better than waiting through the reboot that seems to be required after it fails. But maybe future versions of OS X won't require all this extra work...



[ Reply to This | # ]
An AppleScript to mount, run, unmount a disk image
Authored by: rhithyn on Sep 08, '04 12:01:40AM

Thanks a bootload for this script!

I had hacked up another older script I found here to set up a SSH tunnel and mount an encrypted sparseimage before opening Mail. It worked well except if I didn't enter my password on the sparseimage mount fast enough, it would lock up.

This one is patient enough to wait.

Scripts like this are the reason I love this site!



[ Reply to This | # ]
An AppleScript to mount, run, unmount a disk image
Authored by: Christian Leue on Sep 08, '04 01:27:24AM
I achieve basically the same results with the following code:


on idle
	tell application "Finder" to eject "Zoo Tycoon"
	tell application "Finder" to eject "Marine Mania"
	quit
end idle

on run
	set myPath to trim_line((path to me as string), "Zoo Tycoon start.app", 1)
	do shell script ("hdiutil mount \"" & POSIX path of (myPath as string) & "Zoo Tycoon.dmg\"")
	do shell script ("hdiutil mount \"" & POSIX path of (myPath as string) & "Marine Mania.dmg\"")
	set myApp to myPath & "Zoo Tycoon"
	tell application myApp to activate
	idle
end run


on trim_line(this_text, trim_chars, trim_indicator)
	-- 0 = beginning, 1 = end, 2 = both
	set x to the length of the trim_chars
	-- TRIM BEGINNING
	if the trim_indicator is in {0, 2} then
		repeat while this_text begins with the trim_chars
			try
				set this_text to characters (x + 1) thru -1 of this_text as string
			on error
				-- the text contains nothing but the trim characters
				return ""
			end try
		end repeat
	end if
	-- TRIM ENDING
	if the trim_indicator is in {1, 2} then
		repeat while this_text ends with the trim_chars
			try
				set this_text to characters 1 thru -(x + 1) of this_text as string
			on error
				-- the text contains nothing but the trim characters
				return ""
			end try
		end repeat
	end if
	return this_text
end trim_line



[ Reply to This | # ]
An AppleScript to mount, run, unmount a disk image
Authored by: rhithyn on Sep 08, '04 10:03:55AM

One problem:

This will only eject disks that are visible in the desktop view. I have set the name of my mail volume to ".Mail" to keep it off of my desktop, but still have all other mounted images show up. Whenever I try to eject the volume using Finder's "eject" command, it says it can't find the volume, although it is in the disk list.

Any ideas on how to make the finder eject hidden volumes?



[ Reply to This | # ]
An AppleScript to mount, run, unmount a disk image
Authored by: emendelson on Sep 08, '04 02:45:56PM

The script at the top of this story (the original hint) ejects hidden disks because it doesn't use the finder to mount or unmount them - it uses shell scripts.



[ Reply to This | # ]
An AppleScript to mount, run, unmount a disk image
Authored by: rhithyn on Sep 08, '04 07:51:00PM

I should have clarified that I was commenting on Christian Leue's script and not on the original script. Sorry!



[ Reply to This | # ]
An AppleScript to mount, run, unmount a disk image
Authored by: stuming on Sep 09, '04 08:49:10AM

Hi all,

Anyone know how/if I can use the above script to mount and then unmount physical firewire drives?

I have a couple of external disks: one holds all my photos, mp3s, movies, audio etc, the other is the backup drive to which Backup 2 rights to when backing up my system.

I week or so ago, I discovered that iTunes had somehow found the backed up library and was using that as the default. To stop this is generally eject the backup drive off the desktop, but of course, I have to remember to mount it again before backup 2 runs. I forget quite often!

I'd like to do this automatically if possible.

Stuart



[ Reply to This | # ]
An AppleScript to mount, run, unmount a disk image
Authored by: rhithyn on Sep 09, '04 09:58:22AM

This would be a more significant issue with iTunes configuration and should probably be addressed as such. I suspect that you did a search for music since backing up and iTunes found your backup on top of your regular source.

What you should do to fix the problem is the following:

  1. Download and install this script from Doug's Applescripts for iTunes (Super Remove Dead Tracks).
  2. Under "Advanced" tab in iTunes Preferences, verify that "iTunes Music folder location" is set to where you want to keep your music. Usually, having the "Copy files to iTunes Music folder when adding to library" turned on is a good idea as well, but it isn't necessary.
  3. Verify that your original folder has all of the music.
  4. Temporarily unmount your Backup2 drive
  5. Run the Super Remove Dead Tracks script in iTunes.

That should remove any references to the new folder. Note that the script only removes the references from the iTunes library and not the files (at least last time I used it) so it should be safe to run once the volume is unmounted.

If the music is not in your library, try consolidating your music after step 2 above (in iTunes, use "Consolidate Library..." under "Advanced" menu) and then you may want to check for duplicate songs using another script from Doug's site.



[ Reply to This | # ]
An AppleScript to mount, run, unmount a disk image
Authored by: mmatties on Sep 10, '04 02:59:03PM

I used the ideas from your script and just did

tell application "Finder"
try
open item "Macintosh HD:applications:images:CalculatingCrew.dmg"
end try
repeat until name of every disk contains "Crew"
delay 1
end repeat
open item "Crew:Calculating Crew"
end tell

and it works great - for MOST applications. But some mount the image and then say that "the CD can't be found. Please insert it and try again."

Can anyone help me with this problem? Thanks!



[ Reply to This | # ]
An AppleScript to mount, run, unmount a disk image
Authored by: emendelson on Sep 11, '04 08:12:41AM

In reply to mmatties's question: the problem you came across (the app can't find the image) is EXACTLY what the script in the hint is designed to fix. It fixes the problem by NOT using the Finder to mount the disk, but by using a shell script. Try the script in the hint itself and see whether it solves the problem for you. (But reboot first, because after the application can't find the image, it will never see it again until you reboot.)



[ Reply to This | # ]
An AppleScript to mount, run, unmount a disk image
Authored by: rattler14 on Sep 10, '04 07:24:12PM

A more flexible perl solution, in case you have multiple mounts, in multiple locations. Also remote friendly

[code]
#!/usr/bin/perl

$command=$ARGV[0];
$name=$ARGV[1];


### Add your disk image name, and location here
%directories=("all","~/Desktop/all.dmg","none","~/Desktop/none.dmg");

if($command eq "mount")
{ system "hdiutil mount $directories{$name}"; }
elsif($command eq "unmount")
{
$mount_data = `mount`;
($dev)=($mount_data=~/(\/dev\/disk\d{1,2}).*?\/Volumes\/$name/);
system "hdiutil detach $dev";
}
else
{ print "sorry, must select mount or unmount";}
[/code]

Save as diskmnt.pl, make it executible by running chmod a+x diskmnt.pl, then dump it into /usr/local/bin
Works great for me, and is a bit more compact and easier for a command line guy like me to understand.

Any thoughts suggestions, let me know

cheers

-rick



[ Reply to This | # ]
An AppleScript to mount, run, unmount a disk image
Authored by: toor on Oct 06, '04 09:08:11PM

Re: rattler14's script -

Handy, thanks. However, a few comments/questions:
1) When I tried to put the file in /usr/local/bin/ is gave me a permissions error and I had to login as root to place it. Is that normal?

2) Being a bit of a *nix newbie is there any other command to run it than:
/usr/local/bin/diskmnt.pl ? Maybe my path needs updating?

3) I would like to use this ( or something like it ) to unmount one of my main drive's three partitions. Is that possible? Currently when I run it, it unmounts both of the non-running partitions.

Thanks for your time and help in these matters.



[ Reply to This | # ]
An AppleScript to mount, run, unmount a disk image
Authored by: oshea on Oct 08, '04 11:08:36PM
It doesn't look like the script will unmount correctly if the mounted image name contains a space. The first 'hdiutil unmount...' fails because it thinks you're trying to pass it two different image names.

Any idea what the proper syntax is to work around this?

Relevant bits:
 property diskname : "Nemo UWF"
 do shell script ("hdiutil unmount /Volumes/" & diskname & " -force")


[ Reply to This | # ]
An AppleScript to mount, run, unmount a disk image
Authored by: emendelson on Oct 10, '04 10:18:41AM

The solution to oshea's question seems to be something like this:

If you need to mount a disk image whose name in the Finder has a space or ampersand or other non-alphanumeric character, then you probably need to use two different variables instead of the one "diskname" variable in the original script.

The variable diskname should be the name in the Finder, as in the original script, and this should be used in the pure-Applescript parts of the script (the parts that don't use shell scripts).

Another variable would be called something like unixdiskname, and this would use escaped characters, like this:

unixdiskname: "Nemo\ UMF"

or

unixdiskname: "This\ \&\ That"

Then, in the original script's shell script commands, replace "diskname" with "unixdiskname". I haven't tested this enough to be certain it works, but I think it will.



[ Reply to This | # ]
An AppleScript to mount, run, unmount a disk image
Authored by: jbreazeale on May 09, '05 03:09:48AM
I tried your suggestion for escaping the spaces and ScriptEditor gave me an error. The script line:
    property unixdiskname : "Reader\ Rabbit\ Toddler"
was diagnosed with the error:
    Syntax Error
    Expected """ but found unknown token.
Could you (or somebody else) give me a way around this issue?

[ Reply to This | # ]
A way to speed up the original script
Authored by: emendelson on Oct 10, '04 10:24:40AM

Kevin O'Shea pointed out (in a private message) that the original script can be speeded up by modifying the shell script with "hdiutil attach" - just add the -noverify switch at the end of the shell script, so that the last bit in quotation marks reads:

" -mount required -noverify"

Seems to work for me.



[ Reply to This | # ]
An AppleScript to mount, run, unmount a disk image
Authored by: jbreazeale on May 21, '05 04:13:54AM
I tried to get the AppleScript working. I could get the disk image to mount and the application to start but after the application quit the disk image was still mounted. I came up with a different solution that works pretty well for my needs. What I wanted was a way to avoid having my children handle CDs and launching applications. To solve this problem I built bootstrap AppleScript application icon and name set to be the same as the program that it ultimately launches. The AppleScript application calls a the mntrun shell script that adds canned, location-specific text to the application and disk image names then mntrun calls the script that does the real work, mntlauncher. Mntlauncher mounts the disk drive image, starts the application, waits for the application to finish, then unmounts the disk image. Here's the AppleScript that launches "Reader Rabbit's Toddler":

property launcher : "/Applications/Launchers/mntrun"
property itemname : "The Learning Company/Reader Rabbit Toddler/Reader Rabbit's Toddler"
property diskpath : "Reader Rabbit Toddler.img"

on run
	tell application "Finder"
		do shell script (launcher & "  \"" & itemname & "\" \"" & diskpath & "\"")
	end tell
end run
Here's the text of /Applications/Launchers/mntrun:

#!/bin/bash

#
# mntrun
#
# Front end script that accepts an application name and disk image name
# and calls mntlaunch.  This script is an intermediary to mntrun.
#
launcher=/Applications/Launchers/mntlaunch

itemname="$1"
diskpath="$2"

#
# Customize these two lines to launch applications from a standard
# location and to find disk images in a standard location.
#
application_path="/Applications/$itemname"
fulldiskpath="/Volumes/160GB HD/CD Cache/Educational/originals/$diskpath"

#
# Call the launcher script!
#
$launcher "$application_path" "$fulldiskpath"
Here's the text of /Applications/Launchers/mntlaunch:

#!/bin/bash

#
# mntlaunch
#
# This script will mount a volume image file, run an application, then
# will unmount the mounted volume.  The inputs are full path names to
# the application and image file.
#

function cleanup
{
    rm -f /tmp/$PROG.*.$$
}

PROG=`basename $0`
TMPFILE1=/tmp/$PROG.1.$$

trap 'cleanup; exit 1' 1 2 3 15
itempath="$1"
volume="$2"

#
# Collect the volume path as the disk image is mounted
#
export COLUMNS=1024
hdiutil attach "$volume" -mount required -noverify 2>&1 >$TMPFILE1
return_code=$?
if [ $return_code -ne 0 ]; then
    echo "$PROG: Mount failed, status=$return_code" >&2
    exit $return_code
fi

# 
# Disk image mounted!  Launch application.
#
open "$itempath"
return_code=$?
if [ $return_code -ne 0 ]; then
    echo "$PROG: Open failed, status=$return_code" >&2
    exit $return_code
fi

#
# Application launched.  Wait for application to exit.
#
sleep 1
while ((1))
do
    #
    # Count to see how many times the application appears.  If does
    # appear one time there must be a problem or it has exited.
    #
    count=`ps -ax | grep "$itempath" | grep -v grep | wc -l`
    if [ $count -ne 1 ]; then
        break
    fi
    sleep 1
done

#
# Get the full path name of the mounted disk image.
#
disk=`grep ^/dev/disk $TMPFILE1 | cut -d' ' -f1`

#
# Unmount the disk image.
#
hdiutil unmount $disk -force -quiet
hdiutil detach $disk -force -quiet

cleanup
In mntrun you can see the script is designed for applications to be located in the /Applications folder. The AppleScript application merely needs to make reference to the application path relative to /Applications. In mntrun you can also see that I keep my disk images in /Volumes/160GB HD/CD Cache/Educational/originals, so mntrun creates the proper full path name to the disk image for mntlaunch. If the user wishes to run an application on the mount volume one merely needs to refer to an application path such as "../Volumes/Volume Name/Application Path". The "../Volumes/Volume Name" is the path to the mounted volume and "Application Path" is the path to the application within the mounted volume. It's all quite a hack, but at least I can stop having to make CD copies for my children (3 and 6 years old)!

[ Reply to This | # ]
An AppleScript to mount, run, unmount a disk image
Authored by: bryanc on Jan 04, '07 06:40:49PM

The reason for this is that there are two layers of escaping needed. 1) Applescript uses the \ character to escape things in any string; and 2) the shell itself uses \ to escape things.

So, when inside a string Applescript sees the \ character, it wants the next character to be a valid escape character. You actually want a literal \ in the string (so that the shell will see it, and treat is as an escape character).

property unixdiskname : "Reader\\ Rabbit\\ Toddler"

will do the trick for you.



[ Reply to This | # ]
An AppleScript to mount, run, unmount a disk image
Authored by: bryanc on Jan 04, '07 06:42:54PM
That was supposed to be a reply to this thread of comments earlier on the page.

[ Reply to This | # ]