macos开机自启动需分清launch agents(用户级)和launch daemons(系统级):用launchctl list查看运行服务,ls命令定位plist文件,load/unload加载卸载,start/stop启停,plutil校验格式,并通过console或log命令排查日志。
要通过终端指令管理 macos 所有开机自启动守护服务,核心是用好 launchctl 命令,并分清服务类型(launch daemons 系统级 / launch agents 用户级)、存放路径和权限要求。图形界面设置(如“登录项”)只管用户级 gui 应用,而真正底层的守护进程必须靠终端操作。
识别当前所有自启动服务
先看清系统里到底有哪些服务在运行或已注册:
- 查看当前用户加载的所有代理:launchctl list | grep -v '^-' | grep -v '0x'(过滤掉系统内部条目)
- 列出系统级守护进程(需 sudo):sudo launchctl list | grep -v '^-'
- 快速定位自定义服务:ls ~/Library/LaunchAgents/ /Library/LaunchDaemons/ 2>/dev/null(显示实际存在的 plist 文件)
- 查某个服务详细状态:launchctl print gui/$(id -u)/com.example.app(用户级)或 launchctl print system/com.example.service(系统级)
加载与卸载守护服务
加载(enable)和卸载(disable)决定服务是否随系统/用户登录自动启用:
- 加载用户级代理(无需 sudo):launchctl load ~/Library/LaunchAgents/com.example.app.plist
- 卸载用户级代理:launchctl unload ~/Library/LaunchAgents/com.example.app.plist
- 加载系统级守护(必须 sudo):sudo launchctl load /Library/LaunchDaemons/com.example.daemon.plist
- 卸载系统级守护:sudo launchctl unload /Library/LaunchDaemons/com.example.daemon.plist
- ⚠️ 注意:/System/Library/ 下的 plist 受 SIP 保护,不可 load/unload;修改 /Library/LaunchDaemons/ 必须用 sudo,且文件权限应为 644,属主为 root:wheel
启停正在运行的服务
加载 plist 不等于立即运行,还需手动触发 start/stop:
- 启动服务:launchctl start com.example.app(用户级)或 sudo launchctl start com.example.daemon(系统级)
- 停止服务:launchctl stop com.example.app 或 sudo launchctl stop com.example.daemon
- 服务名来自 plist 中
Label 的值,不是文件名 —— 可用 cat xxx.plist | grep -A1 Label 快速确认 - 若配置了
KeepAlive ,stop 后会自动重启;需先 unload 或设 KeepAlive false 再停
调试与日志排查
服务不启动?没反应?得看输出和错误:
- 查看标准输出/错误路径(需在 plist 中预先配置):cat /path/to/stdout.log
- 在“控制台”App 中筛选进程名,或执行:log show --predicate 'process == "com.example.app"' --last 1h
- 验证 plist 格式是否合法:plutil -lint ~/Library/LaunchAgents/com.example.app.plist
- 检查环境变量是否缺失:若脚本依赖 $PATH 或 $HOME,需在 plist 中显式写
EnvironmentVariables PATH /usr/local/bin:/opt/homebrew/bin:...











