I'm running OS 10.7.5 on an October 2008 unibody MacBook, and I would like to somehow get my computer to run a script whenever I press the power button, instead of prompting me if I want to turn my laptop off.

My situation is as follows: simply closing the cover of the MacBook sometimes results in Sleep mode not initiating, and the computer then closed gets very hot (not sure what's going on in there). I solved this problem by pressing the Power button and choosing "Sleep" each time I want to put it to sleep, and then closing the lid.

Now, as I use TrueCrypt, I want to unmount all my TrueCrypt drives whenever I put my laptop to sleep. So when I press the power button, I wish to run the following commands:

truecrypt -d
osascript -e 'tell application "System Events" to sleep'

In this case it doesn't have to give me any type of prompt, I would like the commands to be executed directly. Any suggestions appreciated!

EDIT: I guess it doesn't have to be the power button that I press when this script is executed. That is, if I can get the execution of these two commands associated with a certain combination of keys, I would be just as happy.

  • Would it also be okay to create an icon in your dock that runs these commands when you click it? That would be easy...
    – Vincent
    Mar 21 '13 at 4:44

KeyRemap4MacBook can apparently remap the power button for some Macs, but it didn't work with my iMac.

<autogen>__ConsumerToKey__ ConsumerKeyCode::POWER, KeyCode::F19</autogen>

If you just want to assign a shortcut to a script, see this question.

  • Ok, but this just assigns the result of pressing the F19 button (which I don't actually see on my keyboard, I only have F1-F12) to the Power button, whereas I want a script to be executed (say, located at /Users/Me/Desktop/custom.sh). What's the syntax for that? Mar 21 '13 at 14:43
  • KeyRemap4MacBook doesn't support running scripts, so you'd need a different application for assigning F19 to some script (see the linked question).
    – Lri
    Mar 21 '13 at 14:53
  • Thanks, but it didn't work for me either. I ended up using Automator to and Sys Prefs to associate the script to a key combination. Mar 21 '13 at 15:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .