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

Mount / unmount external drive for Backup use Apps
I use Apple's Backup program to back up files from my computer every night to an external hard drive (that has only one partition) reserved for backups. Problem is that I don't like having it mounted all of the time, since it spins up whenever I save or open a document, etc. Instead, I prefer to mount/unmount the drive just prior to and after Backup runs, so that's it's not in the way when I don't need it.
  1. With the drive mounted, open Disk Utility and select the drive partition that will be the destination of the backup.
  2. Select Info, and make note of the Disk Identifier. In my case, it's disk1s10.
  3. Edit your crontab to contain the lines:
    59 3 * * * /usr/sbin/diskutil mount /dev/disk1s10
    15 4 * * * /usr/sbin/diskutil eject '/Volumes/The Annex'
    Replace the end of the first line, disk1s10 with the drive identifier from step one. Replace the end of the second line, '/Volumes/The Annex' with '/Volumes/name of your backup hard drive' (the quotes will handle any spaces in the drive's name).
Assuming that I do a backup at 4am, the first line will mount the disk at 3:59am. The second line will unmount the disk at 4:15am. Adjust the times accordingly, particularly the unmount time if you have longer backups. If you're unfamiliar with the vi editor in Terminal, select all of the text above and copy it. In terminal, type crontab -e, type i (insert), then paste. Hit Escape and type :q -- you're done!

Note that this won't be effective if you're backing up to a drive with more than one partition. Also, make sure that the unmounting time is somewhat beyond the time that your backups regularly finish. I've looked at the history of my backups and found that it always finishes in less than 10 minutes.
    •    
  • Currently 2.50 / 5
  You rated: 5 / 5 (6 votes cast)
 
[51,647 views]  

Mount / unmount external drive for Backup use | 12 comments | Create New Account
Click here to return to the 'Mount / unmount external drive for Backup use' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
Mount / unmount external drive for Backup use
Authored by: kainewynd2 on Mar 16, '07 08:12:28AM

Just out of curiosity, what backup program are you talking about?

It's still a useful idea.



[ Reply to This | # ]
Mount / unmount external drive for Backup use
Authored by: rflorence on Mar 16, '07 08:28:03AM

It is probably not a good idea to select an arbitrary time period for which the drive is mounted and hope that it is long enough to complete the backup. Why not use a backup script that would make the backup contingent on the mount and the dismount contingent on the completion of the backup?

mount ... && backup ... && umount ...

Or, launchd includes a mechanism that initiates actions when a specific directory has changed, which could be used to automatically start the backup when the backup volume is mounted.

- Ronald Florence



[ Reply to This | # ]
Mount / unmount external drive for Backup use
Authored by: ctierney on Mar 16, '07 08:30:11AM
Thanks for the hint. I've recently been experimenting with dismounting drives from shell scripts. Here's another method of getting the device name using the volume name:
mount | sed -ne "s#^([^ t]{1,}).*your hard drive name[ t].*#1#p"
--
Cole

[ Reply to This | # ]
don't forget to save changes in vi
Authored by: ctierney on Mar 16, '07 08:32:32AM

I think you meant to write: Hit Escape and type :wq to finish editting.



[ Reply to This | # ]
Mount / unmount external drive for Backup use
Authored by: zebrum on Mar 16, '07 08:42:41AM

You should try SuperDuper it mounts and unmounts the drive automatically and even sleeps your computer when the backup completes.



[ Reply to This | # ]
Mount / unmount external drive for Backup use
Authored by: Spartacus on Mar 16, '07 01:32:03PM

Maybe people don't want to change their whole backup strategy for a single feature like this, especially if there is a backup-software–independant work around like this one.



[ Reply to This | # ]
Mount / unmount external drive for Backup use
Authored by: ssevenup on Mar 16, '07 09:42:06AM
I have been working on an rsync script and I believe you will find that the device name will change depending on the circumstances. We have automount to thank for that. I am not yet mounting/unmounting my disk but I am using `/usr/sbin/diskutil info /Volumes/ROCSTOR | grep UUID | awk '{print $2}' | grep xxxx-xxxxxx-xxxxxx-xxxxxx` to verify the script only runs when the exact disk volume needed is there. I found that without a good sanity check rsync would mirror my directory back onto the local disk in "/Volumes" because automount sometimes leaves a directory behind after the volume is unmounted. And if that happens at the same time another device is using the same device name you have a problem. So I look for the disk UUID, and that the target directory is present. I will probably be adding mount/unmount at some point. More importantly, I need a "busy" UI that a) informs when the sync is running and b) allows one to interrupt when needed. Unmounting between syncs also allows the user to yank the firewire (or USB) cable without ejecting the disk. This lessens the likelihood of disk corruption.

---
Mark Moorcroft
ELORET Corp. - NASA/Ames RC
Sys. Admin.

[ Reply to This | # ]

Using Applescript
Authored by: theDan on Mar 16, '07 10:38:37AM

I had a similar dillema, although in my situation it was a network file server who had a dedicated Backup drive.

I wrote a simple enough applescript that launches at login, following this logic:
(I use variables for the backup program's name and the server and the backup drive, and you can modify those on your own)

if backupapp is not running and backupdisk is not mounted
quit

if backupapp is running and backupdisk is not mounted
mount backupdisk

if backupapp is not running and backupdisk is mounted
unmount backupdisk

if bakupapp is running and backupdisk is mounted
check every 10 seconds if appname is running

With this script, I was able to set my backup to start at 7:00AM, and anytime i logged in after then, it would launch itself. This script, upon seeing backupapp running, but no disk mounted, will look in the variables for the server name and disk name, and then extract the username/password stored in your keychain and use that. I used this method so i didn't have to hardcode usernames and passwords into the script.

The first time it is run, it will ask you for permission to access your keychain, to use an item in your keychain, and once more on top of that. For the script to work, you must select allow once or allow always, otherwise the script is unable to access the login info for your server.

Here it is:
(I used Growl for notification, because dialog boxes are terrible, but if you do not have Growl, i recommend getting it.)
<code>
-- VERSION
set ScriptVersion to "v0.9"
set startDelay to 1
set sampleDelay to 5
-- SERVER VARIABLES
set AppName to "Application you use to backup"
set ServerName to "Name of Server, as it would appear in your keychain. Basically the Bonjour address without the .local"
set ServerURL to "afp://" & ServerName & ".local"
set VolumeName to "The name of the shared volume you wish to mount"
set VolumeURL to ServerURL & "/" & VolumeName
set UnmountCMD to "umount " & "/Volumes/" & VolumeName

-- ERROR MESSAGES
set UnmountError to "Volume could not be unmounted, Most likely, this is because files are still open.
Please quit any applications that may be accessing the volume
and click OK.

If you do not wish to unmount the volume right now,
click Cancel and unmount the volume manually later."

set KeychainError to "There was an error accessing your keychain for the login information. You may not have a keychain for this server.
Please mount the volume using the Finder and check the 'Remember Password' box in the login dialog to create a keychain."

set MountError to "The volume could not be mounted. Please verify that:" & "
The URL for the volume is " & VolumeURL & ".
The server and this computer are on the same local network, and that the server is on with AFP enabled."



-- FUNCTION
-- Function to check if App is running, returns count of every app named AppName, 0 if none
on getAppStatus(AppName)
tell application "System Events"
set AppRunning to count (every process whose name is equal to AppName)
return AppRunning
end tell
end getAppStatus

-- Function to see if volume VolumeName is mounted. Returns 0 for not mounted, 1 for is mounted.
on volumeMounted(VolumeName)
tell application "Finder"
if (exists disk VolumeName) then
return 1
else
return 0
end if
end tell
end volumeMounted

-- GROWL NOTIFY
tell application "GrowlHelperApp"
-- All notifications
set the allNotificationsList to ¬
{"Update", "Error"}
-- Enabled notifications
set the enabledNotificationsList to ¬
{"Update", "Error"}
-- Registration
register as application ¬
"Backup Network Mount" all notifications allNotificationsList ¬
default notifications enabledNotificationsList ¬
icon of application AppName
-- Startup Notification
notify with name "Update" title "Backup Script Loaded..." description "Backup Network Mount Script loaded." application name "Backup Network Mount"
end tell
on gnotify(gTitle, gMessage, gType)
tell application "GrowlHelperApp"
notify with name gType title gTitle description gMessage application name "Backup Network Mount" icon of application "Backup"
end tell
end gnotify

--SCRIPT
-- Wait xx seconds to allow time for Backup to launch
delay (delay)
-- If App is not running and the volume not mounted after this, send notifiction and exit
if volumeMounted(VolumeName) + getAppStatus(AppName) = 0 then
gnotify("Nothing to do", AppName & " is not running, and " & VolumeName & " is not mounted. Ending Script.", "Error")
else
-- If the app is running
if getAppStatus(AppName) > 0 then
-- If the volume is not mounted
if volumeMounted(VolumeName) = 0 then
gnotify(AppName & " Running...", "Mounting " & VolumeName, "Update")
try
gnotify("Getting Keychain Info", "Acessing the login information for " & ServerName, "Update")
tell application "Keychain Scripting"
set serverKey to first key of current keychain whose name is ServerName
set UserName to account of serverKey
set PWD to password of serverKey
end tell
on error
gnotify("Keychain Error...", "There was an error accessing the login information in your keychain.", "Error")
display dialog KeychainError
end try
-- log mounting info
gnotify("Attempting to Mount", "Connecting as " & UserName, "Update")
-- Mount the volume
try
mount volume VolumeURL as user name UserName with password PWD
gnotify("Connected Successfully...", "Volume " & VolumeName & " on " & ServerName & " is now mounted.", "Update")
on error
gnotify("Error Mounting " & VolumeName & "...", "There was an error mounting the network volume.", "Error.")
display dialog MountError buttons ["Quit"]
-- quit
end try
end if
end if
-- Check periodically if the app is running
gnotify("Waiting for Backup to Complete...", "Volume " & VolumeName & " will be unmounted once " & AppName & " quits.", "Update")
repeat while getAppStatus(AppName) > 0
tell application "Finder"
delay sampleDelay
end tell
end repeat
gnotify(AppName & " quit.", "Unmounting " & VolumeName & "...", "Update")
-- Once the app has quit, unmount the Volume if it is mounted
if volumeMounted(VolumeName) = 1 then
-- Warn User
gnotify("Unmounting...", "Unmounting " & VolumeName & " because " & AppName & " is no longer running.", "Update")
-- While Disk is mounted, try to unmount and display a error message.
repeat while volumeMounted(VolumeName) is 1
tell application "Finder"
try
do shell script UnmountCMD
on error
tell application "Finder"
activate
display dialog UnmountError
gnotify("Unmounting Failed...", "There was an error Unmounting " & VolumeName, "Error")
end tell
end try
end tell
end repeat
end if
end if
</code>

Here is a version for people who don't care about being notified, even if the script fails. This script is totally silent, not even beeps.

<code>
-- SERVER VARIABLES
set AppName to "Application you use to backup"
set ServerName to "Name of Server, as it would appear in your keychain. Basically the Bonjour address without the .local"
set ServerURL to "afp://" & ServerName & ".local"
set VolumeName to "The name of the shared volume you wish to mount"
set VolumeURL to ServerURL & "/" & VolumeName
set UnmountCMD to "umount " & "/Volumes/" & VolumeName

-- FUNCTION
-- Function to check if App is running, returns count of every app named AppName, 0 if none
on getAppStatus(AppName)
tell application "System Events"
set AppRunning to count (every process whose name is equal to AppName)
return AppRunning
end tell
end getAppStatus

-- Function to see if volume VolumeName is mounted. Returns 0 for not mounted, 1 for is mounted.
on volumeMounted(VolumeName)
tell application "Finder"
if (exists disk VolumeName) then
return 1
else
return 0
end if
end tell
end volumeMounted

-- SCRIPT
-- If the app is running
if getAppStatus(AppName) > 0 then
-- If the volume is not mounted, display a Dialog Box informing the user that the volume is being mounted
if volumeMounted(VolumeName) = 0 then
tell application "Finder"
try
tell application "Keychain Scripting"
set serverKey to first key of current keychain whose name is ServerName
set UserName to account of serverKey
set PWD to password of serverKey
end tell
end try
-- Mount the volume
try
mount volume VolumeURL as user name UserName with password PWD
on error
quit
end try
end tell
end if
end if
-- Check periodically if the app is running
repeat while getAppStatus(AppName) > 0
tell application "Finder"
delay 1
end tell
end repeat

-- Once the app has quit, unmount the Volume if it is mounted
if volumeMounted(VolumeName) = 1 then
-- While Disk is mounted, try to unmount and display a error message.
repeat while volumeMounted(VolumeName) is 1
tell application "Finder"
try
do shell script UnmountCMD
end try
end tell
end repeat
end if
</code>

Copy and paste the script you would like to use into Script Editor, insert your netwoork server information, and then save as an application bundle, without a startup screen.

Then, add it as a login item and you are ready to go!

May you be forever backed up.

-Dan



[ Reply to This | # ]
Mount / unmount external drive for Backup use
Authored by: steresi on Mar 16, '07 12:43:12PM
This previous hint contains a Perl script that can mount disks based on their visible name rather than device name. I've been using the script posted by user "fix" for a year or two.

[ Reply to This | # ]
Mount / unmount external drive for Backup use
Authored by: paulw on May 20, '07 10:11:04PM
I came up with a script that does the same thing but instead of needing to set times, it watches for your backup utility, and when it sees that it's running, it mounts the backup volume. Vice versa when backup utility quits.

Thread here:

http://www.macosxhints.com/article.php?story=20060308154312630&query=mount%2Bpartition

[ Reply to This | # ]
Mount / unmount external drive for Backup use
Authored by: tbaur on Jun 07, '07 10:27:33PM
#!/bin/bash

# Copyright (c) 2007, panaso.com
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of the  nor the
#       names of its contributors may be used to endorse or promote products
#       derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY panaso.com ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL panaso.com BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


# ==> Backup using rsync to defined mountpoint:/path
#     ...mount before backup, unmount when completed
#     version 0.9, this code is not supported.
#
# - create a .backup file on the destination (extra validation)
# - update the applicable variables: src/dst/name/log
# - adjust the rsync flags if needed
# - how logging is done could be more pretty, but it's all good
#
# run via crontab(1) as needed:
#     * 2 * * * /path/to/script


SRC=/Volumes/
DST=/Volumes/
NAME=
log=

# delete/comment out the following after updating variables
  exit 1


DEVICE=`diskutil list|grep $NAME|awk '{print $6}'`
PROC=`ps auwx | grep "rsync" | grep -v grep | wc -l`
TOP='1'

if test $PROC -lt $TOP ; then
	echo "=============================================" >> $log
	echo "=> Backup start: `date`" >> $log
	if [ -z $DEVICE ]; then
		echo "=> ERROR: Volume -> $NAME is NOT connected - exiting" >> $log
		exit 1
	else
		if [ ! -z `ls -1 /Volumes/ | grep $NAME` ] ; then
			echo "=> Volume -> $NAME is already mounted" >> $log
			if [ ! -f $DST/.backup ]; then
				echo "=> ERROR: Volume did not mount properly (missing .backup?) - exiting" >> $log
				diskutil unmount /Volumes/$NAME
				if [ -d $DST ]; then
					rmdir $DST
				fi
				exit 1
			fi
		else
			echo "=> Checking -> $NAME at /dev/$DEVICE" >> $log
			if [ `file /dev/$DEVICE | awk '{print $2}'` = "block" ] ; then
				echo "=> Mounting -> $NAME at /dev/$DEVICE" >> $log
				if [ -d $DST ]; then
					rmdir $DST
				fi
				diskutil mount /dev/$DEVICE
				if [ -f $DST/.backup ]; then
					echo "=> Volume -> $NAME mounted properly" >> $log
					else
					echo "=> ERROR: Volume did not mount properly (missing .backup?) - exiting" >> $log
					diskutil unmount /Volumes/$NAME
					if [ -d $DST ]; then
						rmdir $DST
					fi
					exit 1
				fi
				else
				echo "=> ERROR: /dev/$DEVICE does not appear to be a disk partition - exiting" >> $log
				exit 1
			fi
		fi
	fi
	echo "=> Starting rsync of $SRC to $DST" >> $log
	rsync --delete -av $SRC/* $DST >> $log
	echo "=> Rsync completed ..." >> $log
	echo "=> Unmounting -> $NAME at /dev/$DEVICE" >> $log
	diskutil unmount /Volumes/$NAME
	if [ -d $DST ]; then
		rmdir $DST
	fi
	echo "=> Backup finished: `date`" >> $log
	exit 1
else
	echo "=> WARNING: Backup already running: `date`" >> $log
	exit 1
fi


[ Reply to This | # ]
Mount / unmount external drive for Backup use
Authored by: tbaur on Jun 08, '07 02:41:23AM
couple minor fixes -- namely when run by cron, it's probable you won't have a path, so we'll just use full path for diskutil/rsync. cheers.
--- backup.old  2007-06-08 02:35:45.000000000 -0700
+++ backup      2007-06-08 02:36:10.000000000 -0700
@@ -28,7 +28,7 @@
 
 # ==> Backup using rsync to defined mountpoint:/path
 #     ...mount before backup, unmount when completed
-#     version 0.9, this code is not supported.
+#     version 0.9.1, this code is not supported.
 #
 # - create a .backup file on the destination (extra validation)
 # - update the applicable variables: src/dst/name/log
@@ -36,11 +36,11 @@
 # - how logging is done could be more pretty, but it's all good
 #
 # run via crontab(1) as needed:
-#     * 2 * * * /path/to/script
+#     0 2 * * * /path/to/script
 
 
-SRC=/Volumes/
-DST=/Volumes/
+SRC=
+DST=
 NAME=
 log=
 
@@ -48,7 +48,7 @@
   exit 1
 
 
-DEVICE=`diskutil list|grep $NAME|awk '{print $6}'`
+DEVICE=`/usr/sbin/diskutil list|grep $NAME|awk '{print $6}'`
 PROC=`ps auwx | grep "rsync" | grep -v grep | wc -l`
 TOP='1'
 
@@ -63,7 +63,7 @@
                        echo "=> Volume -> $NAME is already mounted" >> $log
                        if [ ! -f $DST/.backup ]; then
                                echo "=> ERROR: Volume did not mount properly (missing .backup?) - exiting" >> $log
-                               diskutil unmount /Volumes/$NAME
+                               /usr/sbin/diskutil unmount /Volumes/$NAME
                                if [ -d $DST ]; then
                                        rmdir $DST
                                fi
@@ -76,12 +76,12 @@
                                if [ -d $DST ]; then
                                        rmdir $DST
                                fi
-                               diskutil mount /dev/$DEVICE
+                               /usr/sbin/diskutil mount /dev/$DEVICE
                                if [ -f $DST/.backup ]; then
                                        echo "=> Volume -> $NAME mounted properly" >> $log
                                        else
                                        echo "=> ERROR: Volume did not mount properly (missing .backup?) - exiting" >> $log
-                                       diskutil unmount /Volumes/$NAME
+                                       /usr/sbin/diskutil unmount /Volumes/$NAME
                                        if [ -d $DST ]; then
                                                rmdir $DST
                                        fi
@@ -94,10 +94,10 @@
                fi
        fi
        echo "=> Starting rsync of $SRC to $DST" >> $log
-       rsync --delete -av $SRC/* $DST >> $log
+       /usr/bin/rsync --delete -av $SRC/* $DST >> $log
        echo "=> Rsync completed ..." >> $log
        echo "=> Unmounting -> $NAME at /dev/$DEVICE" >> $log
-       diskutil unmount /Volumes/$NAME
+       /usr/sbin/diskutil unmount /Volumes/$NAME
        if [ -d $DST ]; then
                rmdir $DST
        fi


[ Reply to This | # ]