中文 English

MacOS custom login and logout scripts

Published: 2021-11-04

Login and Logout Scripts

重要提示: There are many reasons to avoid using login and logout scripts:

  • Login and logout scripts are a deprecated technique. In most cases, you should use a launchd job instead, as described in Creating a Launch Daemon and Agent.
  • Login and logout scripts run as root, which is a security risk.
  • Only one of each script can be installed at a time. They are intended for system administrators; application developers should not use them in released software.

One way to run applications at login is to launch them using a custom shell script. When creating script files, keep the following points in mind:

Use the defaults tool to install your login script. Create a script file and place it in a directory accessible to all users. In a terminal, install the script using the following command (where /path/to/script is the full path to the script file):

To remove this hook, remove this property:

Use the same procedure to add or remove a logout hook, but type LogoutHook instead of LoginHook.

Note: This method will not work if the plist file com.apple.loginwindow does not exist. This file (/var/root/Library/Preferences/com.apple.loginwindow.plist) does not exist on a fresh installation until the user changes the login window settings (such as turning on Fast User Switching).

If you must install the startup script programmatically, you should consider providing a copy of this file containing the default configuration options. Then, if the file does not exist, copy the default configuration file into place before running defaults. Likewise, application developers are strongly advised not to use login or logout scripts, as only one such script can be installed.

sudo defaults write com.apple.loginwindow LoginHook /path/to/script
sudo defaults delete com.apple.loginwindow LoginHook

Reference article