Applescript to Unmount Volumes Matching a Pattern

applescriptmountstorage

I have several backup offline and bootable backup volumes on a disk , and I would like to unmount all of them at startup. They all start with the name "Backup"

I've found the following Applescript courtesy of https://discussions.apple.com/thread/5102909, which is very efficient, but would appreciate help to add in wildcards. I would like it to unmount any volumes that being with "Backup"

set volname to "Backup" -- # name of target volume  

set p to (POSIX path of (volname & ":" as alias))'s text 1 thru -2

set sh to "diskutil umount " & quoted form of p & " &> /dev/null &"

do shell script sh

I feel like it should be possible, but always get messed up with the correct syntax. Your wisdom would be very appreciated!

*** Edit
My disk & volume structure looks like this:

disk2s1 EFI
disk2s2 Backup System 10May19
disk2s3 Backup Archives

I unmount the volumes at startup, so the disk can spin down. Chronosync automatically mounts/unmounts as needed during backup operations.

Best Answer

This is how I'd do it... The following example AppleScript code will unmount any mounted disk that starts with "Backup":

set listOfDisks to list disks
set listOfDisksToUnmount to {}

repeat with thisDisk in listOfDisks
    if thisDisk starts with "Backup" then
        copy contents of thisDisk to end of listOfDisksToUnmount
    end if
end repeat

if listOfDisksToUnmount is not {} then
    repeat with thisDisk in listOfDisksToUnmount
        do shell script "diskutil unmount /Volumes/" & thisDisk's quoted form
    end repeat
end if

Note: If you have an issue with the unmount verb with diskutil, try unmountDisk instead.

Note: contents in copy contents of thisDisk to end of listOfDisksToUnmount doesn't copy the contents of the disk, it copies the contents of the list item, which is the name of the disk.


Note: The example AppleScript code is just that and does not contain any error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5, with the value of the delay set appropriately.