Mac OS X -- Running a Command at Login and Logout

One way to run applications at login time is to launch them using a LoginHook. Similarly, a LogoutHook can be used when a successful logoff happens. However, this is a deprecated approach, that has been replaced by LaunchAgents that are run via the `launchd` system process.

A LoginHook is a program (typically script) that runs as root before the login process continues. Typically located under /Library/Scripts

There is a single LoginHook per system, and a single LogoutHook per system. They are intended for system administration, unlike LaunchAgents, which can also be provided by individual users.

When creating your LoginHook file, keep the following in mind:

  • In your script, the variable $1 returns the short name of the user who is logging in.
  • Other login actions wait until your hook finishes executing. Therefore, your program needs to run quickly.

Use the `defaults` tool to install your LoginHook. Create the script file and put it in a directory that is accessible to all users. In Terminal, use the following command to install the script (where /path/to/script is the full path to your script file):

sudo defaults write com.apple.loginwindow LoginHook /path/to/script
To remove this hook, delete the property:
sudo defaults delete com.apple.loginwindow LoginHook
Use the same procedure to add or remove a logout hook, but type LogoutHook instead of LoginHook.

Note: If no plist file exists for com.apple.loginwindow, this method will not work. This file (/var/root/Library/Preferences/com.apple.loginwindow.plist) does not exist on a fresh installation until the user changes a login window setting (such as turning on fast user switching). If you must install startup scripts programmatically, you should consider providing a copy of this file containing the default configuration options. Then, if the file does not exist, copy that default configuration file into place before running defaults. Again, application developers are strongly discouraged from using login or logout scripts, because only one such script may be installed.

Login hooks were deprecated in 10.4 in favor of launchd. To run a script at login, save a plist like this as ~/Library/LaunchAgents/test.plist. It's loaded on the next login even if you don't run launchctl load ~/Library/LaunchAgents/test.plist.

-- EdwardChrzanowski - 2014-09-19

Edit | Attach | Watch | Print version | History: r5 < r4 < r3 < r2 < r1 | Backlinks | Raw View | WYSIWYG | More topic actions
Topic revision: r5 - 2015-03-26 - EdwardChrzanowski
 
This site is powered by the TWiki collaboration platform Powered by PerlCopyright © 2008-2024 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback