Skip to content

Instantly share code, notes, and snippets.

@vadimpiven
Last active January 7, 2024 10:00
Show Gist options
  • Save vadimpiven/9bb974857226976329a07ac387d3e97a to your computer and use it in GitHub Desktop.
Save vadimpiven/9bb974857226976329a07ac387d3e97a to your computer and use it in GitHub Desktop.
MacOS add application (Example.app) to autostart
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.example.app.startup</string>
<key>AssociatedBundleIdentifiers</key>
<array>
<string>com.example.app</string>
</array>
<key>Program</key>
<string>/Applications/Example.app/Contents/MacOS/Example</string>
<key>ProgramArguments</key>
<array>
<string>/Applications/Example.app/Contents/MacOS/Example</string>
</array>
<key>Disabled</key>
<false/>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<dict>
<key>Crashed</key>
<true/>
</dict>
<key>ProcessType</key>
<string>Interactive</string>
<key>LimitLoadToSessionType</key>
<string>Aqua</string>
<key>AbandonProcessGroup</key>
<true/>
<key>ExitTimeOut</key>
<integer>5</integer>
</dict>
</plist>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleName</key>
<string>Example</string>
...
<key>LSUIElement</key>
<string>1</string>
</dict>
</plist>
#!/bin/bash
# SPDX-License-Identifier: MIT
# MIT Software License: https://opensource.org/licenses/MIT
# Copyright Vadim Piven <vadim@piven.tech>
set -ex
LIBRARY_DIR="/Users/$USER/Library"
AGENTS_DIR="$LIBRARY_DIR/LaunchAgents"
STARTUP_SERVICE="com.example.app.startup"
STARTUP_PLIST_NAME="$STARTUP_SERVICE.plist"
STARTUP_PLIST_SRC="$PWD/$STARTUP_PLIST_NAME"
STARTUP_PLIST_DST="$AGENTS_DIR/$STARTUP_PLIST_NAME"
PREFERENCES_DIR="$LIBRARY_DIR/Preferences"
if [ -e "$STARTUP_PLIST_DST" ]; then
sudo -u "$USER" launchctl bootout "gui/$(id -u "$USER")" "$STARTUP_PLIST_DST" || true
fi
osascript -e "quit app \"Example.app\"" || true
if [ ! -d "$AGENTS_DIR" ]; then
mkdir -p "$AGENTS_DIR"
chown "$USER" "$AGENTS_DIR"
fi
cp -f "$STARTUP_PLIST_SRC" "$STARTUP_PLIST_DST"
chmod -x "$STARTUP_PLIST_DST"
chown "$USER" "$STARTUP_PLIST_DST"
sudo -u "$USER" launchctl bootstrap "gui/$(id -u "$USER")" "$STARTUP_PLIST_DST" \
|| (sudo -u "$USER" launchctl enable "gui/$(id -u "$USER")/$STARTUP_SERVICE" \
&& sudo -u "$USER" launchctl bootstrap "gui/$(id -u "$USER")" "$STARTUP_PLIST_DST") \
|| sudo -u "$USER" launchctl kickstart "gui/$(id -u "$USER")/$STARTUP_SERVICE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment