How to Run a Shell Script When Logging Out

As a Mac administrator it can be useful to be run a shell script each time a user logs out. This allows a script to clean up temporary files, back up changes, and restore sane defaults for the next user.

Let's walk through how to schedule a shell script to run after a user logs out of Mac OS X. Our shell script is going to be very simple but you can make yours as complex as needs be.

We are going to start by using the Schedule Assistant built into Power Manager and then we are going to customise the event using the Event Editor.

Scheduling a Log Out Shell Script

  1. Launch System Preferences and select Power Manager.
  2. Click Add… to create a new event.
    Launch Power Manager and click the Add button
  3. Choose the template Run a script.
    Select the Run a Script task in the Schedule Assistant
  4. Click Continue to the Script step.
  5. Copy and paste your shell script into the Script step.

    #!/bin/sh
    
    touch /tmp/lastlogout.txt

    The shell script can be run as the root user, as a normal user, or even as whoever is currently logged in at the time. For this script, we have set the Environment to Super User (root).

    Copy and paste in your shell script
  6. Click Continue to the When step.
  7. Adjust the time and date to the distant future; this trigger will be replaced in a later step.
    Change the date to a time in the future
  8. Continue through the remaining steps until your event is created.

    Continue passed the Constraints step
    Name and description your Power Manager event
    Confirm the event and click Add

    With these steps completed, you will have a basic Power Manager event queued up. This event includes your shell script but is not yet triggered after log out.

    The event has been created but is not yet finished

    Let's customise this event using the Event Editor. We want to replace the Date and Time based trigger with a Log Out trigger.

  9. Hold down the Option key on the keyboard and double-click on your event; the Event Editor will now appear.
    Your event in Power Manager's Event Editor
  10. Delete the existing Date and Time trigger; use the Action cog and select Delete….
    Delete the date and time trigger from the event
    The event with the date and time triggered deleted
  11. Add a new Log Out trigger; use the Add a trigger pop-up menu and select Log Out.
    Add a Log Out trigger to your event
  12. Click Save to save your changes and finish editing the event.
    Click Save to save the changes and close the Event Editor
The finished event to run a shell script after log out is ready

Your new Power Manager event is ready and will now run every time a user logs out.

This article was posted in , , and and tagged .

Published by Graham Miln on