launchctl - macOS


Overview

The launchctl command in macOS is a powerful tool used for managing launchd, a system and session manager that operates at the back-end of macOS. This utility is used to load, unload daemons/agents, and generally control macOS services. It is used in both system-wide contexts and user-specific instances, making it essential for tasks related to service management, such as starting or stopping background services, or modifying how services run at boot or login.

Syntax

The general syntax for launchctl is as follows:

launchctl subcommand [options | arguments]

Here, subcommand defines the specific operation you want to perform, which varies depending on what you want to manage (services, daemons or agents).

Options/Flags

Here are some commonly used subcommands and flags in launchctl:

  • load: Loads the specified configuration file or directory of configuration files.
  • unload: Unloads the specified configuration file or directory of configuration files.
  • list: Lists all currently loaded launchd jobs if no argument is provided.
  • start: Starts the specified job.
  • stop: Stops the specified job.
  • enable: Enables the specified job.
  • disable: Disables the specified job.
  • bootout: Unloads and removes the service definition from the boot context.

These subcommands are used in conjunction with various options such as paths to service configuration files or identifiers to manipulate the services.

Examples

Loading a service:

launchctl load /System/Library/LaunchAgents/com.example.myagent.plist

Unloading a service:

launchctl unload /System/Library/LaunchAgents/com.example.myagent.plist

Listing all services:

launchctl list

Starting a specific job:

launchctl start com.example.myagent

Common Issues

  • Permissions Error: When you attempt to manipulate system-level services without sufficient permissions. To resolve this, run launchctl with sudo for system-level commands.
  • Configuration Errors: Errors in the plist configuration files can prevent services from loading correctly. Double-check your plist syntax.

Integration

launchctl can be combined with other shell commands or scripts to automate macOS tasks. For example, to check the status of all loaded jobs and grep for a specific service:

launchctl list | grep "com.example.myagent"

This command chain is useful in scripts where automatic checks on service statuses are required.

  • systemctl: Similar command for systemd in Linux.
  • cron: For managing scheduled tasks, though unrelated in functionality, it is often used in tandem for time-based job scheduling.

For more details and advanced options, consult the man launchctl in the terminal or the official Apple developer documentation.