Skip to content

Instantly share code, notes, and snippets.

@genevera
Last active April 13, 2019 20:54
Show Gist options
  • Save genevera/377fc3bafc74911b7e112345816ccd47 to your computer and use it in GitHub Desktop.
Save genevera/377fc3bafc74911b7e112345816ccd47 to your computer and use it in GitHub Desktop.
ZSH function to stop and restart a service under launchd - written on high sierra 10.13.6 for zsh 5.7.1
################################################################################
# restarts a service in launchd. assumes you have
# https://github.com/MarkTiedemann/countdown-cli installed. but will run `sleep`
# if you don't.
#
# usage: svc_bounce domain/svc_target timeout
# timeout is needed so launchd can shut the service down gracefully.
################################################################################
function svc_bounce() {
local -r svc="${1}";
local -r timeout="${2:-10}"
local sudo_cmd;
local svc_dir="Library/LaunchAgents";
local svc_dirs=( "${HOME}/${svc_dir}" "${HOME}/${svc_dir/Agent/Daemon}" "/${svc_dir}" "/${svc_dir/Agent/Daemon}" "/System/${svc_dir}" "/System/${svc_dir/Agent/Daemon}" );
local err=1
## zsh indices are 1-indexed.
local counter=1
local pause_cmd="$(command -v countdown) -s";
## do we need to sudo?
if [[ "${svc#system/}" != "${svc}" ]];
then
sudo_cmd="/usr/bin/sudo";
svc_dir="/Library/LaunchAgents";
fi;
### countdown or sleep?
[[ ${pause_cmd} == "" ]] && pause_cmd="$(command -v sleep)";
## bootout/stop svc, wait if needed
eval "${sudo_cmd}" /bin/launchctl bootout "${svc}" 2>/dev/null;
if [[ "${timeout}" -gt 0 ]];
then
echo "Booting out ${svc##*/}. We will wait ${timeout} seconds to restart.";
eval "${pause_cmd}" "${timeout}";
echo "Let's begin.";
fi;
## step thru potential locations of svc, bootstrap and kickstart.
while [[ "${err}" -gt 0 ]] && [[ "${counter}" -lt "${#svc_dirs[@]}" ]];
do
eval "${sudo_cmd}" /bin/launchctl bootstrap "${svc%/*}" "${svc_dirs[${counter}]}/${svc##*/}.plist" 2>/dev/null;
let err="${?}";
if [ "${err}" -gt 0 ]; then
echo "plist not found in ${svc_dirs[${counter}]}";
else
echo "bootstrapping ${svc} from ${svc_dirs[${counter}]}/${svc##*/}.plist...";
break;
fi;
let counter="$(( ${counter} + 1 ))";
done;
if [[ ${err} -gt 0 ]] || [[ ! ${counter} -lt ${#svc_dirs[@]} ]]; then
echo "could not bootstrap ${svc}!";
else
echo "Service ${svc##*/} bootstrapped. Kickstarting.";
eval "${sudo_cmd}" /bin/launchctl kickstart -pk "${svc}";
fi;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment