How do I unmount a drive with a script?

Solution 1:

You don't need sudo to unmount a drive.

Use diskutil

The following command ejects the volume Backup:

diskutil eject /Volumes/Backup

This should do it, although (IIRC) you might want…

diskutil unmount /Volumes/Backup

…to make it easier to re-mount without having to physically disconnect/reconnect the drive.

Ejecting All Disks

If you want to make sure you have ejected all of your disks, you can try this:

osascript -e 'tell application "Finder" to eject (every disk whose ejectable is true)'

Third Party Tool: Mountain

There is also Mountain which will automate this for you.

Third Party Tool: Keyboard Maestro

Above all other ideas, I would recommend Keyboard Maestro which can do all of these things on sleep, and remount your drive on wake, plus 1,000 other things.

Solution 2:

You can have a "$" in your echo statement, you just have to escape it.

$ echo "$abc123"
                         <-----Results in a blank line

However

$ echo "\$abc123"
$abc123                  <-----Works

Also, instead of using double quotes, use single quotes to encapsulate your string:

$echo '$abc123'
$abc123                  <-----Works

Basically, what's happening is that within double quotes ("), it preserves the literal values of the characters with the exception of the dollar sign ("$"), the tilde ("~"), and the back slash ("\"). When you enclose your text within a single quote ('), it preserves all characters, period.

Modify Your sudoers file.

With that cleared up, don't save/use passwords in clear text in your script as it's equally insecure!

Instead, what you should do is modify your sudoers file so that you grant "no password" access to that command only.

username ALL = (ALL) ALL
username ALL = (root) NOPASSWD: /path/to/foo/bar/command

With this method, you leave your system security intact and allow for the use of sudo with no password for this one particular command.