【macOS】开机启动项

Posted by 西维蜀黍 on 2022-02-26, Last Modified on 2022-04-05
Folder Usage
/System/Library/LaunchDaemons Apple-supplied system daemons
/System/Library/LaunchAgents Apple-supplied agents that apply to all users on a per-user basis
/Library/LaunchDaemons Third-party system daemons
/Library/LaunchAgents Third-party agents that apply to all users on a per-user basis
~/Library/LaunchAgents Third-party agents that apply only to the logged-in user

Approach 1 - Via System Preferences > Accounts > Login items

  • start Automator.app
  • select Application
  • click Show library in the toolbar (if hidden)
  • add Run shell script (from the Actions/Utilities)
  • copy & paste your script into the window
  • test it
  • save somewhere (for example you can make an Applications folder in your HOME, you will get an your_name.app)
  • go to System Preferences -> Accounts -> Login items
  • add this app
  • test & done ;)

a Variant

To launch commands when logging in, you can do this:

  • Create a text file containing your commands (bash script):

    #!/bin/bash
    
    # Start the MongoDB server
    /Applications/MongoDB/bin/mongod --dbpath /usr/local/mongo/data --fork --logpath /usr/local/mongo/log
    
  • Save this file in ~/Library/Startup.cmd

  • You can test it by double-clicking the file in the Finder

  • Make it executable: chmod +x ~/Library/Startup.cmd

  • Add this file in System Preferences > Accounts > Login items

Approach 2 - Via launchctl

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
   <key>Label</key>
   <string>com.user.loginbashscript</string>
   <key>ProgramArguments</key>
   <array><string>/path/to/executable/script.sh</string></array>
   <key>RunAtLoad</key>
   <true/>
</dict>
</plist>

Replace the <string> after the Program key with your desired command (note that any script referenced by that command must be executable: chmod a+x /path/to/executable/script.sh to ensure it is for all users).

Save as ~/Library/LaunchAgents/com.user.loginscript.plist

# make it executable with 
$ sudo chmod +x /path/to/executable/script.sh

# and owned by root:wheel with 
$ sudo chown root:wheel /path/to/executable/script.sh 

Run launchctl load ~/Library/LaunchAgents/com.user.loginscript.plist and log out/in to test (or to test directly, run launchctl start com.user.loginscript)

Tail /var/log/system.log for error messages.

The key is that this is a User-specific launchd entry, so it will be run on login for the given user. System-specific launch daemons (placed in /Library/LaunchDaemons) are run on boot.

# make it executable with 
$ sudo chmod +x /Library/LaunchDaemons/com.user.loginscript.plist
# and owned by root:wheel with 
$ sudo chown root:wheel /Library/LaunchDaemons/com.user.loginscript.plist

# run it onboot
$ sudo launchctl load /Library/LaunchDaemons/com.user.loginscript.plist

Reference