Is it possible to execute a script/command right before OS X is shutting down or restarting?

I'd like to run sudo apachectl stop to stop apache from auto-starting.

  • 2
    possible duplicate of Make a script/app run on logout Oct 29, 2013 at 2:39
  • 1
    This question here asks about shutdown/restart, the question linked in the comment about logout. These are different scenarios so let's leave the questions separated for the moment.
    – nohillside
    Oct 29, 2013 at 9:07

2 Answers 2


You can use a logout hook:

sudo defaults write com.apple.loginwindow LogoutHook ~/.logouthook
echo $'#!/bin/bash\napachectl stop' > ~/.logouthook
chmod +x ~/.logouthook

The value of the LogoutHook key can only be a path to an executable and not a shell command. The logout hook is run with superuser privileges so you don't need sudo.

The defaults command modifies /var/root/Library/Preferences/com.apple.loginwindow.plist. Adding a LogoutHook key to /Library/Preferences/com.apple.loginwindow.plist doesn't work.

If a logout hook takes long enough to run, a gray screen is shown until the logout hook terminates. There doesn't seem to be any time limit after which logout hooks are forced to terminate.

Logout hooks were deprecated in 10.4, but I haven't figured out any way to run programs on logout reliably with launchd. I haven't gotten rc.local.shutdown to work either. I don't know any way to run a logout hook before shutting down or restarting but not before logging out.


If you want Apache stop starting from your computer on boot you probably want to unload the appropiate .plist with launchctl:

Open a terminal, then
sudo launchctl unload -w /System/Library/LaunchDaemons/org.apache.httpd.plist

  • did you mean /usr/sbin/apachectl?
    – napcae
    Oct 29, 2013 at 12:23
  • apachectl stop just runs launchctl unload -w /System/Library/LaunchDaemons/org.apache.httpd.plist on OS X. See cat /usr/sbin/apachectl.
    – Lri
    Oct 29, 2013 at 16:34
  • While this doesn't answer the actual question as asked, this is the best solution to the problem. Remove the .plist and apache will no longer start on boot.
    – l008com
    Feb 11, 2018 at 10:53

You must log in to answer this question.

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