Adding Startup Scripts to Launch Daemon on Mac OS X Sierra 10.12.6

Task in Hand

Lets Start

vim ~/scripts/startup/startup.sh
#!bin/bash
#Start Mariadb Server only if it is not running
if [ “$(ps -ef | grep -v grep | grep mariadb | wc -l)” -le 0 ]
then # Note starting mariadb not as a sudoer
mariadb start
echo "Mariadb Server Started"
else
echo "Mariadb Server Already Running"
fi
chmod +x ~/scripts/startup/startup.sh

The main difference is that an agent is run on behalf of the logged in user while a daemon runs on behalf of the root user or any user you specify with the UserName key.

/Library/LaunchDaemons/ 
/Library/LaunchAgents/
sudo vim /Library/LaunchDaemons/com.startup.plist

Configuration of the plist file will vary upon your use case. The list of properties that can be configured is again nicely illustrated under the Configuration section on launchd.info

<?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>EnvironmentVariables</key>
<dict>
<key>PATH</key>
<string>/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:</string>
</dict>
<key>Label</key>
<string>com.startup</string>
<key>Program</key>
<string>/Users/admin/Scripts/startup/startup.sh</string>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<false/>
<key>LaunchOnlyOnce</key>
<true/>
<key>StandardOutPath</key>
<string>/tmp/startup.stdout</string>
<key>StandardErrorPath</key>
<string>/tmp/startup.stderr</string>
<key>UserName</key>
<string>admin</string>
<key>GroupName</key>
<string>admin</string>
<key>InitGroups</key>
<true/>
</dict>
</plist>
# -w flag permanently adds the plist to the Launch Daemon
sudo launchctl load -w /Library/LaunchDaemons/com.startup.plist
# -w flag permanently remove the plist to the Launch Daemon
sudo launchctl unload -w /Library/LaunchDaemons/com.startup.plist
# Will only temporarily stop. It will again auto launch unless the service is explicitly stopped using launchctl unload command 
mariadb stop
#You can stop the launchctl process by
#sudo launchctl stop /Library/LaunchDaemons/com.startup.plist
#You can start the launchctl process by
#sudo launchctl start -w /Library/LaunchDaemons/com.startup.plist

--

--

--

Founder & CEO at ARITS Limited. More at https://www.aritsltd.com

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Fahim Hossain

Fahim Hossain

Founder & CEO at ARITS Limited. More at https://www.aritsltd.com

More from Medium

Automation and Accessibility in depth with your Mac !!!

How to Install a .IPA file using the CLI on macOS?

Article image

Review Apps is a game changer

Error parsing LocalFile: ‘\android\app\src\main\AndroidManifest.xml’