MacBook Air/Pro: run script upon lid close

closed-clamshelllidmacbook proSecuritysleep-wake

How can one configure MacOS (10.8 or higher) to automatically and immediately call a user-designated script (probably a bash script) upon the user closing the display lid of a MacBook Air or Pro?

Details.

I want to do this because in some scenarios my MacBook Air 2013 running 10.8.5 does not immediately sleep/lock the screen upon lid close (possibly because a VPN client is trying to open a connection). As such, I want the system to immediately execute a script which calls this screen-saving-and-locking procedure upon lid close. However, I don't know how to call scripts upon display-lid closing.

Best Answer

There does not seem to be a way for a program to get notified when the lid is closed. However, the state of the lid can be monitored periodically (and in this particular case, every second) and actions taken based on the lid state.

I do not know of any program that can provide a complete solution for your need, but you can use the following information to build a solution yourself.

  1. Download this clamshellstate.pl perl script
  2. You can run it in Terminal (under /Applications/Utilities) like:

    ./clamshellstate.pl 1  
    

    to get an output like "Open" or "Closed" indicating the current lid state

  3. Create a shell script like (substitute script-to-run with a shell script you'd like to run):

    ./clamshellstate.pl 1 | grep Closed > /dev/null && *script-to-run*
    
  4. Configure this script to run once every second using launchd.plist. Or use Lingon to easily configure launchd.plist.

Note: Instead of clamshellstate.pl, you can also use the following command in Terminal:

ioreg -r -k AppleClamshellState | grep '"AppleClamshellState" = Yes' | cut -f2 -d"="

to get a "Yes" for the closed state and a "No" for the open state.