A script to open/close an external CD/DVD via keyboard

Feb 15, '05 09:39:00AM

Contributed by: dmmorse

I have both an internal DVD drive on my G4 and an external CD burner connected via Firewire. The internal drive can always be opened using the F12 key, as this is built into OS X. I wanted the same, or at least similar, functionality for my external CD drive. I looked all over for an easy way to accomplish this task, but could not find any. So, in the end, I had to create my own.

First, I realized that the drutil terminal command allowed me to do exactly what I wanted as long as I knew the drive number of my external CD drive. For example, to eject drive 2, the command is drutil eject -drive 2, and to close drive 2 the command is drutil tray close -drive 2.

At first I thought, "Wow, that makes it easy!" All I needed to do then was hook these two commands into separate keyboard shortcuts using an application like Spark. I chose F6 for the Eject command and Option-F6 for the Close command. But not so fast. I soon discovered that my two drives did not always have the same drive number after a restart. This added a new wrinkle to my task. After some research into some advanced (at least it was advanced to me) Bash scripting, here is what I came up with.

First, you need to do a drutil list in Terminal to see your multiple drives. Mine looks like this:

   Vendor   Product           Rev   Bus       SupportLevel
1  PIONEER  DVD-RW  DVR-107D  1.13  ATAPI     Apple Shipping
2  LITE-ON  LTR-52327S        QS03  FireWire  Apple Supported
Take note of the vendor for your external drive. Above, my external drive vendor is listed as "LITE-ON" (capitalization is important!). Next, here is the script I came up with to eject and close the drive:
#!/bin/bash

driveselect=`/usr/bin/drutil list|grep "LITE-ON"|sed 's/  LITE-ON.*$//'`
if [ "$1" = "-c" ]; then
  drutil tray close -drive $driveselect;
elif [ "$1" = "-o" ]; then
  drutil eject -drive $driveselect;
fi
Notice that where LITE-ON appears in the code above, you need to substitute the name of the vendor for your particular external drive.

You can create this using your favorite Terminal text editor, or a free program like Bare Bones' TextWrangler. Give the file a name and save it. If you want to access this script via the Terminal, you need to save it somewhere in your defined file path. Personally, I named mine sesame and saved it to /Users/Shared/bin/ (a directory I created long ago for such purposes). Next make the file executable by doing a chmod a+x sesame in the Terminal. Now, using terminal, sesame -o ejects the drive and sesame -c closes the drive.

Finally, using Spark and a do shell script command, I hooked sesame -o to F6 and sesame -c to option-F6. Now go relax and enjoy your new keyboard shortcuts!

Comments (15)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20050210030547149