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

Mount and unmount external drives easily via AppleScript Storage Devices
I like to eject my external drives because they slow down my mac when they spin up, but I want to have an easy way to access them if I need to. I wrote a little AppleScript that will toggle the mount status of the drive (if it's mounted, it will eject, if it's unmounted, it will mount).

To run the script, use the script menu at the right of the menu bar, or bind it to a hot key using a Quicksilver-type app. Be sure to change 'YourDiskNameHere' to the name of the volume you're working with.

The script can be easily adapted to only eject, or only mount the drive. You can also tweak it to display a Mount/Unmount dialog if you wish.
set diskName to "YourDiskNameHere"
tell application "Finder"
 if disk diskName exists then
  eject disk diskName
 else
  tell current application
   set deviceLine to (do shell script "diskutil list | grep \"" & diskName & "\" | awk '{ print $NF }' }'")
   if deviceLine = "" then
    display dialog "The disk \"" & diskName & "\" cannot be found." buttons {"OK"} default button 1 with title "Error" with icon caution
   end if
   set foundDisks to paragraphs of deviceLine
   repeat with i from 1 to number of items in foundDisks
    set this_item to item i of foundDisks
    if this_item contains "disk" then
     do shell script "diskutil mountDisk /dev/" & this_item
    end if
   end repeat
  end tell
 end if
end tell


[crarko adds: Seems to work fine.

Note: A minor correction to the script was made per request of the author, based on a simplification given in a comment below.]
    •    
  • Currently 2.92 / 5
  • 1
  • 2
  • 3
  • 4
  • 5
  (12 votes cast)
 
[36,180 views]  

Mount and unmount external drives easily via AppleScript | 19 comments | Create New Account
Click here to return to the 'Mount and unmount external drives easily via AppleScript ' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
Mount and unmount external drives easily via AppleScript
Authored by: ac3320 on Feb 13, '12 09:07:54AM

1. Is there a way to add multiple external volumes to this applescript? For instance I have a "Time Machine" volume and an "External HD" volume both connected via USB... I'd like to just eject both if both are present, or just one if only one is present.

2. Also, is there a way to get the script to do the same with Network attached volumes?

I have created my own AppleScript to mount (but not unmount) my HD attached to my AEBS. It'd be great to have one ultra script that mounts/unmounts any volume (network or directly attached via USB/FW)! :)

Here is my own AppleScript for the mounting the network volume:

try
mount volume "afp://Time Capsule._afpovertcp._tcp.local/External HD" as user name "Anthony" with password "password"
on error
return
end try



[ Reply to This | # ]
Mount CIFS Shares.app
Authored by: dzurn on Feb 14, '12 01:08:11PM
Here's my code I've developed to mount several cifs shares (mine are for DFS network shares)

-- mount CIFS shares.app
-- D Zurn
-- Edit the section below to add the specific shares you want to mount whenthe app is run.
-- The list of mounted volumes is good, the list of failed mounts sometimes includes 
--    mounts that really DID succeed. So, there's that.
-- After any share fails, you can say "yes" to the question to open the Terminal so you
--   can try to determine why it might not work. 
-- The script also opens the Volumes folder to see if there are 'failed' mount folders 
--   from previous attempts, cluttering up the folder.

-- No attempt is made to remove failed mount folders, as it's too risky for a simple Applescript.

----------------  START OF USER-EDITABLE VARIABLES  ---------------- 

-- Edit this list of volumes to add/remove desired disks
set diskPaths to {ャ
	"cifs://Domain1/Directory1/NetworkShare1", ャ
	"cifs://Dmn2/Dir2/Network%20Share2", ャ
	"cifs://Longer%20Domain%203/Share3"}

----------------  END OF USER-EDITABLE VARIABLES  ---------------- 

set diskNames to {}

local myCR, myLine

set oldDelims to AppleScript's text item delimiters -- save their current state
set AppleScript's text item delimiters to {"/"} -- declare new delimiters

repeat with i from 1 to (count diskPaths)
	set myPieces to every text item of item i of diskPaths
	set myTempPieces to item (count myPieces) of myPieces
	
	-- Use SED to globally replace %20 with a space, for readability
	set end of diskNames to do shell script "echo " & quoted form of myTempPieces & "|sed 's/%20/ /g' "
end repeat

set AppleScript's text item delimiters to oldDelims -- restore them

set myCR to "

"
set myLine to "覧覧覧覧覧"

tell application "Finder"
	set AppleScript's text item delimiters to ", "
	set userAborted to false
	
	set myExistingMounts to (list disks) ------ What do we have already mounted?
	
	set myFailedDisks to "" ------- Keep track of which disk we didn't mount
	set dialogText to ""
	
	repeat with i from 1 to (count diskNames) ------ Loop to mount the volumes
		set thisDiskName to item i of diskNames
		set thisDiskPath to item i of diskPaths
		set currentMounts to do shell script "mount" ----- Get a list of which volumes are currently mounted
		
		if (currentMounts) does not contain thisDiskName then
			-- display dialog ((list disks) as string)
			try
				-- mount volume (myPath & thisDiskPath)
				open location (thisDiskPath)
			on error number n
				display alert ("Error " & n & " for " & thisDiskName)
				if (n is -128) then
					set userAborted to true
					exit repeat
				end if
				if (n is not -35) then
					exit repeat
				end if
			end try
			delay 3
		end if -- if currentMounts does not contain thisDiskName
		
		-- Now check to see if the mounted volume shows up in the Finder...
		-- "list disks" shows us what the Finder thinks is mounted. Not the same as the mount results!
		if (list disks) does not contain thisDiskName then
			tell application "System Events"
				if (exists file ("/Volumes/" & thisDiskName & "/.autodiskmounted")) then
					set dialogText to "AutoDiskMounted volume " & thisDiskName & " found. Fix this." & myCR & myLine & myCR
				end if
			end tell
			
			-- The current disk isn't mounted for whatever reason, so put it in our list of non-mounted disks.
			if ((length of myFailedDisks) is 0) then
				set myFailedDisks to thisDiskName
			else
				set myFailedDisks to myFailedDisks & ", " & thisDiskName
			end if
		end if
		
		-- Continue with the rest of the disk in our list...	
	end repeat
	
	------ Figure out which disks we succeeded in mounting:
	set myFinishedMounts to (list disks)
	
	-- display dialog ((list disks) as string)
	set myNewMountText to ""
	repeat with myIndex from 1 to (count myFinishedMounts)
		set thisMount to item myIndex of myFinishedMounts
		-- display dialog (thisMount as string)
		if myExistingMounts does not contain thisMount then
			if ((length of myNewMountText) is 0) then
				set myNewMountText to thisMount
			else
				set myNewMountText to myNewMountText & ", " & thisMount
			end if
		end if
	end repeat
	
	if ((length of myNewMountText) is 0) then --------- No new mounts
		set dialogText to dialogText & "No additional volumes were mounted." & myCR
		
	else ----- we've got some new mounts
		set dialogText to dialogText & "These volume(s) were successfully mounted:" & myCR & myNewMountText
		
	end if
	
	if ((length of myFailedDisks) is 0) then
		
		------- No failed mounts, list the dialog text and stop
		activate
		display dialog dialogText
		
	else ------ At least 1 mount failed, so display the dialog we've been making and offer to open Terminal
		set dialogText to dialogText & myLine & myCR & "These volumes could not be mounted:"
		set dialogText to dialogText & myCR & myFailedDisks
		set dialogText to dialogText & myCR & "Open Terminal window?"
		try
			activate
			display dialog dialogText buttons {"Open Terminal", "Done"} default button "Done" giving up after 100
			set the user_choice to the button returned of the result
			if (user_choice is "Open Terminal") then
				tell application "Terminal"
					if window frontmost exists then
						tell window frontmost to activate
					end if
					do shell script "open /Volumes"
				end tell
			end if
			
		on error
			display dialog ("Could not open Terminal application")
		end try
	end if
	
end tell
---
Madness takes its toll.
Please have exact change.


[ Reply to This | # ]
Update to unmount internal drives
Authored by: nickv2002 on Feb 13, '12 02:56:49PM
I wanted to use this script to mount and unmount an internal disk partition. Unfortunately, the Apple Script-able Finder does not consider internal partitions ejectable the script would only mount the disk but not unmount it. So I copied the logic from the mounting aspect of the script to have diskutil unmount the disk via a command line call which did the trick. Here's the updated version:

set diskName to "diskname"

tell current application
	set deviceLine to (do shell script "diskutil list | grep \"" & diskName & "\" | awk '{ print substr($0,69,9) }'")
	if deviceLine = "" then
		display dialog "The disk \"" & diskName & "\" cannot be found." buttons {"OK"} default button 1 with title "Error" with icon caution
	end if
	set foundDisks to paragraphs of deviceLine
end tell

tell application "Finder"
	if disk diskName exists then
		tell current application
			repeat with i from 1 to number of items in foundDisks
				set this_item to item i of foundDisks
				if this_item contains "disk" then
					do shell script "diskutil unmount /dev/" & this_item
				end if
			end repeat
		end tell
	else
		tell current application
			repeat with i from 1 to number of items in foundDisks
				set this_item to item i of foundDisks
				if this_item contains "disk" then
					do shell script "diskutil mountDisk /dev/" & this_item
				end if
			end repeat
		end tell
	end if
end tell
Edited on Feb 13, '12 03:18:15PM by nickv2002


[ Reply to This | # ]
Update to unmount internal drives
Authored by: jedics on Apr 11, '12 08:57:44AM

this worked for me but it doesnt seem to spin the drive down like it does when I eject manually from the finder.

anyone else have this problem?



[ Reply to This | # ]
Mount and unmount external drives easily via AppleScript
Authored by: wallybear on Feb 13, '12 04:54:29PM

You can replace

awk '{ print substr($0,69,9) }'

with a cleaner

awk '{ print $NF }'

This command will do the same work (i.e. get the last word of the diskutil output line) without the need to specify the starting column and the lenght of the substring ( that could be different in future releases of diskutil).



[ Reply to This | # ]
Mount and unmount external drives easily via AppleScript
Authored by: Swordfish on Feb 14, '12 07:24:03PM

Whoa thanks! I wasn't aware of this. I know nothing about how "awk" works, I just looked at some example code and hacked it until I got the output I wanted.



[ Reply to This | # ]
Mount and unmount external drives easily via AppleScript
Authored by: The Eck on Feb 13, '12 05:02:34PM

Nice little script, however it seems like others have this base covered: the free iMount and MountnuoM available on MacUpdate; FreeSpace Tab, QuickDisk, and several others on the MAS.



[ Reply to This | # ]
Mount and unmount external drives easily via AppleScript
Authored by: Sven G on Feb 13, '12 11:49:20PM

BTW, on MacUpdate, there is also Semulov (Volumes <--- Semulov: quite clever...), which (un)mounts both local and network drives.



[ Reply to This | # ]
Mount and unmount external drives easily via AppleScript
Authored by: Swordfish on Feb 14, '12 07:13:19PM

Thanks, I was not aware of these apps. However, iMount and MountnuoM don't have a menu item or a keyboard shortcut to mount a specific volume, and FreeSpace Tab, QuickDisk and Semulov can't mount unmounted volumes.



[ Reply to This | # ]
Mount and unmount external drives easily via AppleScript
Authored by: Sven G on Feb 15, '12 12:52:13AM

I haven't yet tried the other apps, but Semulov can definitely mount unmounted local volumes: there is an option in the preferences for showing unmounted volumes (and it even shows the Lion Recovery HD!); however, it doesn't seem to remember unmounted network volumes.



[ Reply to This | # ]
Mount and unmount external drives easily via AppleScript
Authored by: Swordfish on Feb 15, '12 10:39:51AM

My mistake, sorry! I didn't notice that option.



[ Reply to This | # ]
hdd initialized
Authored by: swami on Feb 13, '12 11:52:26PM

i have a caldigit raid 5 which i accidentally initialized. i want to recover my data back. plz tell me a way. list of command i need to follow.



[ Reply to This | # ]
Mount and unmount external drives easily via AppleScript
Authored by: ctapley on Feb 14, '12 06:18:17PM

I have basically the same need for the same reason. I have a MBP 13 2.8 running 10.7.3. I have added a SSD as the primary drive and moved my regular HDD to the optical bay. Most of the stuff I do is on the SSD, but it is nice to have 750 gig of extra storage. However I don't like the extra heat and the slower performance when the HDD is mounted.
My solution was to write a quick script (In Bash because I am old school and not much of a programmer to start with). I called my script mount_HD and it reads like this..


bash-3.2$ more mount_HD

____________________________________
#!/bin/bash

diskutil mountDisk Data_Storage
exit
_____________________________________
I also have an unmount utility as follows..

bash-3.2$ more eject_HD
_____________________________________
#!/bin/bash
diskutil unmountDisk /Volumes/Data_Storage && exit
______________________________________

For each script make it executable like this...

chmod +x {scriptname_here}



For each of these scripts I put them in a directory, made the directory part of my path search and then made an alias of the scripts and dropped it on my desktop. Now I can click the 'Eject' item to unmount, or the 'Mount' button to mount the drive. This is surely not as robust or elegant solution as the other possible solutions offered here, but I think easy to set up on just about any Mac. If you want the terminal session to close the window after it runs the script you can adjust that in the preferences for terminal (Which I did as I rarely use terminal for anything other than running this kind of script). Also you can make the 'unmount' item a startup item and automate the configuration of your system which I did in order to keep the HDD unmounted unless I needed it.

Happy scripting!






[ Reply to This | # ]
Mount and unmount external drives easily via AppleScript
Authored by: llee on Apr 26, '12 07:07:02PM

This time for sure!

------
set alldisks to paragraphs of (do shell script "df -hlg | awk -F/ '/disk*/ {print $5}'")
try
set item 1 of alldisks to ((characters 1 thru -2 of (path to startup disk as string)) as text)
on error
set alldisks to {((characters 1 thru -2 of (path to startup disk as string)) as text)}
end try

set devnames to paragraphs of (do shell script "df -k | awk -F/ '/disk*/ {print $3}'")
set t to {}
repeat with s in devnames
set t to t & (word 1 of s)
end repeat

set the keylist to alldisks
set the foundDisks to t
set answer_list to {}

repeat with the_answer in keylist
set theIndex to my CollectUniqueItemIndex(keylist, (the_answer as string))
set theValue to item theIndex of foundDisks
activate
set answer_list to answer_list & (the_answer as string)
end repeat

set actiondisks to {}
repeat with each_device_id in answer_list
if each_device_id is not in {((characters 1 thru -2 of (path to startup disk as string)) as text), "MobileBackups"} then --then
set theIndex to my CollectUniqueItemIndex(answer_list, (each_device_id as string))
set theValue to item theIndex of foundDisks
set actiondisks to actiondisks & theValue
end if
end repeat

if (count of actiondisks) > 0 then
repeat with myitem in actiondisks
try
do shell script "diskutil unmount /dev/" & myitem
end try
end repeat
else
set dur to paragraphs of (do shell script ャ
"diskutil list -plist|grep -A 1 VolumeName|grep -o '<string>'.*'</string>'|grep -o [^'<'string'>'].*[^'<''/'string'>']")
set foundDisks to {}
repeat with i in dur
if i is not in {((characters 1 thru -2 of (path to startup disk as string)) as text), "MobileBackups"} then
set deviceLine to (do shell script "diskutil list | grep \"" & i & "\" | awk '{ print $NF }'")
set actiondisks to actiondisks & (paragraphs of deviceLine)
else
--set namecount to namecount - 1
end if
end repeat
repeat with myitem in actiondisks
try
do shell script "diskutil mountDisk /dev/" & myitem
end try
end repeat
end if

on CollectUniqueItemIndex(theList, theItem) -- the Item can be string, number, constant, app object or list
local aListMember
repeat with i from 1 to (count theList)
set aListMember to item i of theList
if aListMember = theItem then
set theIndex to i
exit repeat
end if
end repeat
return theIndex
end CollectUniqueItemIndex
------



[ Reply to This | # ]
Mount and unmount external drives easily via AppleScript
Authored by: tingo on Feb 19, '12 03:32:56AM

The original script by Swordfish doesn't work for me (10.6.8). nickv2002's version does work, but only for the couple of USB devices I've tested it with. My main Firewire device gives a "cannot be found" message. I wonder if that's because there's a non-English character () in its name. Any idea? I have not a clue how Apple script works...



[ Reply to This | # ]
Typo
Authored by: stomper9248 on Feb 22, '12 05:46:26PM

There's a typo in the script "{ print $NF }' }" should be "{ print $NF }". (without the quotes)



[ Reply to This | # ]
Typo
Authored by: tingo on Feb 24, '12 12:39:28PM

This helps, I can unmount the volume, but I still get a "not found" when I try to mount it again.



[ Reply to This | # ]
Mount and unmount external drives easily via AppleScript
Authored by: MacTipster on Jun 02, '13 01:41:46PM

I have tried the following script in AppleScript Editor.app on Mac with OS X 10.8.3 (Mountain Lion) and it does unmount PenDrives, but not the internal iMac disks when booting from an external SSD, which is what I want:

-----------------------------------------
set diskName to "Macintosh HD"
tell application "Finder"
if disk diskName exists then
eject disk diskName
else
tell current application
set deviceLine to (do shell script "diskutil list | grep \"" & diskName & "\" | awk '{ print $NF }'")
if deviceLine = "" then
display dialog "The disk \"" & diskName & "\" cannot be found." buttons {"OK"} default button 1 with title "Error" with icon caution
end if
set foundDisks to paragraphs of deviceLine
repeat with i from 1 to number of items in foundDisks
set this_item to item i of foundDisks
if this_item contains "disk" then
do shell script "diskutil mountDisk /dev/" & this_item
end if
end repeat
end tell
end if
end tell
-----------------------------------------

How to fix it?
Thanks.



[ Reply to This | # ]
Mount and unmount external drives easily via AppleScript
Authored by: MacTipster on Jun 15, '13 05:19:33AM

Best script here:

MERGING two Scripts to Unmount disks except booting disk
https://discussions.apple.com/thread/5102909

Enjoy!



[ Reply to This | # ]